var dbgjBase = 'https://api.dabaigongju.com/plugin';
// 消息提示
var Message = function (msg, type, time, callback) {
  layer.msg(msg, {
      icon: type === 3 ? 7 : type ? type : 1, // 1 成功 2 失败  3 警告(layer为7)
      time: time ? time : 3000
    },
    callback && callback()
  );
}
// 消息弹窗
var MessageBox = function (title, content) {
  layer.alert('信息', {
    title: title + " | 大白工具www.dabaigongju.com",
    content: content
  });
}
// 弹窗
var Dialog = function (title, htmlString, width, height, isShowScroll) {
  layer.closeAll(); //此时你只需要把获得的index，轻轻地赋予layer.close即可
  let titleHtml =
    `<div style="text-align:center">
    <span class="dbgj-title">${title}</span>
    <span class="dbgj-link">大白工具 <span class="link">www.dabaigongju.com</span></span>
  </div>`;
  // 默认隐藏滚动条
  let className = isShowScroll ? 'layui-layer-dbgj-sd layui-layer-dbgj-dialog' : 'layui-layer-dbgj-dialog';
  //自定页
  layer.open({
    type: 1,
    skin: className, //样式类名
    closeBtn: 2, //不显示关闭按钮
    anim: 1,
    area: [`${width}px`, `${height}px`],
    shadeClose: false, //开启遮罩关闭
    title: titleHtml,
    content: htmlString
  });
  $(".layui-layer-dbgj-dialog .layui-layer-content").height(height - 48);
  getSelectTab();
};
function getSelectTab() {
  $(".dbgj-dialog-tabs-box .dialog-tabs").on('click', '.tab', function () {
    let index = $(this).attr("index");
    $(this).addClass("selected").siblings("li.tab").removeClass("selected");
    let showContent = $(this).closest(".dbgj-dialog-tabs-box").find("#dialog-content-" + index);
    showContent.removeClass("dbgj-hide").siblings(".dialog-content").addClass("dbgj-hide");
  });
}
// ajax
var ajaxFetch = function (type, url, params, successCb, errorCb) {
  $.ajax({
    type: type,
    url: url,
    data: params ? JSON.stringify(params) : {},
    dataType: 'json',
    contentType: "application/json;charset=UTF-8",
    headers: {
      "token": localStorage.getItem("dbgjToken") ? localStorage.getItem("dbgjToken") : "",
    },
    success: function (res) {
      const {
        code,
        msg,
        bizStatus
      } = res;
      if (code === "201" || code === "202") {
        dbgjObj.isLogin = false;
        Message(msg, 3, 3000);
        layer.closeAll();
        $("#dbgj-home .dbgj-feature-page").addClass("dbgj-hide")
        $("#dbgj-register-login-page").removeClass("dbgj-hide");
        $("#dbgj-register-login-page .dbgj-login-code-box .refresh-code").removeClass("dbgj-hide").siblings(".scan-code").addClass("dbgj-hide");
        return false;
      } else if (bizStatus === '-1' || code === '-1' || code === '-2') {
        dbgjObj.loadingClose();
        dbgjObj.noTimesAlert();
        return;
      } else if (code === "1") {
        Message(msg, 3, 3000);
      }
      successCb && successCb(res);
    },
    eror: function (err) {
      errorCb && errorCb(err);
    }
  })
}
// 导出excel
var downloadFile = function (url, params, title) {
  dbgjObj.loadingOpen();
  var xhr = new XMLHttpRequest();
  // var formData = new FormData();
  // // 添加请求的参数
  // for (let key in params) {
  //   formData.append([key], params[key]);
  // }
  // 添加请求的方式，地址
  xhr.open("POST", dbgjBase + url, true);
  xhr.setRequestHeader('content-type', 'application/json');
  xhr.setRequestHeader('token', localStorage.getItem("dbgjToken"));
  // 设置responseType
  xhr.responseType = "blob";
  xhr.onload = function (e) {
    dbgjObj.loadingClose();
    var content = xhr.response;
    let fileName = xhr.getResponseHeader("Content-Disposition").match(
      /filename=(\S*)xls/
    )[0];
    // const spTitle = getCommodityTitle();
    const str = fileName.replace(/filename=/, "");
    const fileTitle = decodeURIComponent(title + str);
    // 组装a标签
    var elink = document.createElement("a");
    // 设置下载文件名
    elink.download = fileTitle;
    elink.style.display = "none";
    let blob = new Blob([content]);
    elink.href = URL.createObjectURL(blob);
    document.body.appendChild(elink);
    // 模拟点击事件
    elink.click();
    document.body.removeChild(elink);
  };
  xhr.send(JSON.stringify(params));
}

// 全局对象和公共方法
var dbgjObj = {
  isLogin: false, // 是否登录
  loginTimerId: null, // 扫码登录轮询定时器
  getPayStatusTimeId: null, // 购买套餐获取订单状态的定时器
  isSendCode: false, // 是否成功获取验证码
  DialogIndex: null,
  uuid: null, // 登录的uuid
  aliPhone: null, // 无痕验证出滑块需要重新获取验证码的手机号码
  currentUserInfo: null,
  expireAlertIndex: null, // 到期提示弹窗
  noTimesAlertIndex: null, // 没次数提示弹窗
  // 拖拽事件
  dragMove: function (downDivId, moveDivId) {
    let downDiv = document.getElementById(downDivId);
    let moveDiv = document.getElementById(moveDivId);
    // //点击某物体时，用drag对象即可，move和up是全局区域，
    // 也就是整个文档通用，应该使用document对象而不是drag对象(否则，采用drag对象时物体只能往右方或下方移动)  
    downDiv.onmousedown = function (event) {
      var event = event || window.event; //兼容IE浏览器
      //    鼠标点击物体那一刻相对于物体左侧边框的距离=点击时的位置相对于浏览器最左边的距离-物体左边框相对于浏览器最左边的距离
      var diffX = event.clientX - moveDiv.offsetLeft;
      var diffY = event.clientY - moveDiv.offsetTop;
      if (typeof downDiv.setCapture !== 'undefined') {
        downDiv.setCapture();
      }
      document.onmousemove = function (event) {
        var event = event || window.event;
        var moveX = event.clientX - diffX;
        var moveY = event.clientY - diffY;
        if (moveX < 0) {
          moveX = 0
        } else if (moveX > window.innerWidth - moveDiv.offsetWidth) {
          moveX = window.innerWidth - moveDiv.offsetWidth
        }
        if (moveY < 0) {
          moveY = 0
        } else if (moveY > window.innerHeight - moveDiv.offsetHeight) {
          moveY = window.innerHeight - moveDiv.offsetHeight
        }
        moveDiv.style.left = moveX + 'px';
        moveDiv.style.top = moveY + 'px'
      }
      document.onmouseup = function (event) {
        this.onmousemove = null;
        this.onmouseup = null;
        //修复低版本ie bug  
        if (typeof downDiv.releaseCapture != 'undefined') {
          downDiv.releaseCapture();
        }
      }
    }
  },
  // 取密码
  getPassword: function () {
    let getRememberPwCb = function (e) {
      if (e.data.action === "getRememberPwCb") {
        if (e.data.value.userAccount) {
          const userAccount = e.data.value.userAccount;
          $("#login_username").val(userAccount.userName);
          $("#login_password").val(userAccount.password);
          $("#rememberPw").prop('checked', userAccount.checked);
        }
        window.removeEventListener("message", getRememberPwCb);
      }
    }
    window.addEventListener("message", getRememberPwCb);
    window.postMessage({
      action: "getRememberPw"
    }, "*");
  },
  // 时间戳转日期
  timestampToDate: function (timestamp, onlyDate) {
    if (timestamp.length === 10) {
      timestamp = timestamp * 1000
    }
    let date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
    let Y = date.getFullYear() + '-';
    let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
    let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
    let m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
    let s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
    if (onlyDate) {
      return Y + M + D
    } else {
      return Y + M + D + h + m + s;
    }
  },
  //根据时间判断星期几
  getDateAndWeek: function(timestamp) {  //timedat参数格式：   getWeek（new Date("2017-10-27" )）
    if (timestamp.length === 10) {
      timestamp = timestamp * 1000
    }
    let date = new Date(timestamp);
    let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
    let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
    let m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ' ';
    let week = '';
    if(date.getDay() == 0) week = "星期日";
    if(date.getDay() == 1) week = "星期一";
    if(date.getDay() == 2) week = "星期二";
    if(date.getDay() == 3) week = "星期三";
    if(date.getDay() == 4) week = "星期四";
    if(date.getDay() == 5) week = "星期五";
    if(date.getDay() == 6) week = "星期六";
    return M + D + h + m + week;  
  },
  //检测是否处于天猫商品详情页
  isTmall: function () {
    return window.location.host.indexOf('detail.tmall') !== -1 ? true : false;
  },
  //获取当前页面ID（网址）
  getCurrentPageId: function (url) {
    const reg = new RegExp('[?&]id=([^&#]+)');
    let query = location.href.match(reg);
    if (url) {
      query = url.match(reg);
    }
    const id = query ? query[1] : null;
    return id
  },
  // 生成UUID
  getUuid: function () {
    let s = [];
    let hexDigits = "0123456789abcdef";
    for (let i = 0; i < 36; i++) {
      s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";
    let uuid = s.join("");
    return uuid;
  },
  loadingClose: function () {
    $(".dbgj-loader-bg").hide();
  },
  loadingOpen: function () {
    $(".dbgj-loader-bg").show();
  },
  // 获取当前时间
  getCurrentDate: function () {
    var date = new Date(); //实例一个时间对象；
    var year = date.getFullYear(); //获取系统的年；
    var month = date.getMonth() + 1; //获取系统月份，由于月份是从0开始计算，所以要加1
    var day = date.getDate(); // 获取系统日
    var hour = date.getHours(); //获取系统时间
    var minute = date.getMinutes(); //分
    var second = date.getSeconds(); //秒
    return year + '-' + month + '-' + day + '  ' + hour + ':' + minute + ':' + second;
  },
  // 转文件对象
  getFileResolve: function (url) {
    return new Promise((resolve, reject) => {
      fetch(url)
        .then(res => {
          return res.blob()
        })
        .then(blob => {
          resolve(blob)
        })
        .catch(err => {
          resolve('error')
        })
    })
  },
  // 旺旺中间**
  userNickFilter: function (str) {
    // 隐藏中间旺旺号字符 你***为
    let strVal = str.toString();
    return `${strVal.substring(0, 1)}***${strVal.substring(strVal.length - 1)}`
  },
  //从页面中解析上架时间戳
  analysisPutawayTimestamp: function() {
    let putawayTimestamp = "";
    const tmallReg = /old_quantity=(\d+)&date=(\d+)","valTimeLeft"/;
    if (dbgjObj.isTmall()) {
      putawayTimestamp = document.body.innerHTML.match(tmallReg)[2]
    } else {
      putawayTimestamp = window.g_config.idata.item.dbst
    }
    return putawayTimestamp;
  },
  // 转文件对象
  getFile: function(url) {
    return fetch(url).then(res => {
        return res.blob()
      })
      .then(blob => {
        return blob
      })
  },
  // 打开下载窗口
  openDownloadDialog: function(url, saveName) {
    try {
      //检查
      if (typeof url === 'object' && url instanceof Blob) {
        url = URL.createObjectURL(url); //尝试生成Url地址
      }
    } catch (error) {
      throw error;
    }
    let downloadTag = document.createElement('a');
    downloadTag.href = url;
    downloadTag.download = saveName || '';
    let event;
    if (window.MouseEvent) event = new MouseEvent('click');
    else {
      event = document.createEvent('MouseEvents');
      event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    }
    downloadTag.dispatchEvent(event);
  },
  // 获取商品标题
  getCommodityTitle: function() {
    //获取主机网址
    const host = location.host;
    let title = "";
    if (host.indexOf("taobao") !== -1) {
      title = document
        .querySelector("h3.tb-main-title[data-title]")
        .getAttribute("data-title");
    } else {
      title = document.querySelector(".tb-detail-hd h1").innerText;
    }
    return title;
  },
  // 欠费提醒
  expireAlert: function() {
    layer.close(dbgjObj.expireAlertIndex);
    let endTime = dbgjObj.currentUserInfo.endTime ? dbgjObj.timestampToDate(dbgjObj.currentUserInfo.endTime) : "无"
    let html = `
    <div>
      <div><span>账号：${dbgjObj.currentUserInfo.userName}</span><span></span></div>
      <div><span>到期时间：${endTime}</span><span class="dbgj-ml-10 dbgj-warn-btn" id="expireAlert_renew">点击续费</span></div>
      <div><span>金币余额：${dbgjObj.currentUserInfo.goldCoin}</span><span class="dbgj-ml-10 dbgj-warn-btn" id="expireAlert_payCoin">点击充值</span></div>
    </div>
    `;
    dbgjObj.expireAlertIndex = layer.confirm(html, {
      title: false, //不显示标题
      skin: "layui-layer-btn-red",
      btn: ['关闭'] //按钮
    }, function(){
      layer.close(dbgjObj.expireAlertIndex); //疯狂模式，关闭所有层
    });
  },
  // 没次数提醒
  noTimesAlert: function() {
    getCurrentUserInfo(function() {
      layer.close(dbgjObj.noTimesAlertIndex);
      let level = dbgjObj.currentUserInfo.vipLevel;
      let vipText = level == "1" ? "基础版" : level == "2" ? "豪华版" : level == "3" ? "豪华版" : "游客"
      let endTime = dbgjObj.currentUserInfo.endTime ? dbgjObj.timestampToDate(dbgjObj.currentUserInfo.endTime) : "无"
      let entrancesourceCount = dbgjObj.currentUserInfo.entrancesourceCount ? dbgjObj.currentUserInfo.entrancesourceCount :"0"
      let html = `
      <div>
        <div><span>账号：${dbgjObj.currentUserInfo.userName}</span></div>
        <div><span>版本：${vipText}</span></div>
        <div style="margin-bottom:10px"><span>到期时间：${endTime}</span><span class="dbgj-ml-10 dbgj-warn-btn" id="noTimesAlert_renew">
          <a href="https://www.dabaigongju.com/views/pay/pay.html" target="_blank" style="color:#fff;text-decoration:none">点击续费</a></span></div>
        <div style="margin-bottom:10px"><span>金币余额：${dbgjObj.currentUserInfo.goldCoin}</span><span class="dbgj-ml-10 dbgj-warn-btn" id="noTimesAlert_payCoin">
          <a href="https://www.dabaigongju.com/views/pay/pay.html" target="_blank" style="color:#fff;text-decoration:none">点击充值</a></span></div>
        <div><span>查黑号：${dbgjObj.currentUserInfo.checkCount}次</span><span class="dbgj-ml-5">权重评估：${dbgjObj.currentUserInfo.tagCount}次</span></div>
        <div><span>竞品分析：${dbgjObj.currentUserInfo.analysisCount}次</span><span  class="dbgj-ml-5">流量来源：${entrancesourceCount}次</span></div>
        <div><span>淘客订单：${dbgjObj.currentUserInfo.taokeCount}次</span><span  class="dbgj-ml-5">微信骗子：${dbgjObj.currentUserInfo.cheaterCount}次</span></div>
      </div>`;
      dbgjObj.noTimesAlertIndex = layer.confirm(html, {
        title: false, //不显示标题
        skin: "layui-layer-btn-red",
        btn: ['关闭'] //按钮
      }, function(){
        layer.close(dbgjObj.noTimesAlertIndex); //疯狂模式，关闭所有层
      });
    }) 
  }
}

// 插件初始化先获取token
function crxInit() {
  // 初始化
  $("#dbgj-seller").html(dbgjSeller);
  injectDetails();
  // injectSearchProductItem();
  injectLoading();
  injectNonTraceValidate();
  // 详情页工具2按钮初始化
  detailPageTool2Init();
  // 检查是否在卖家中心
  let isTrade = location.host.indexOf("trade.taobao.com") >= 0 ? true : false;
  if (isTrade) {
    // 加载订单列表
    sellerBgOrderListInit();
  }
  window.postMessage({
    action: "getToken"
  }, "*")
  const hiddenDiv = document.getElementById('dbgjEventDiv');
  hiddenDiv.addEventListener('dbgjSetTokenEvent', function () {
    const eventData = JSON.parse(hiddenDiv.innerText)
    if (eventData.token === "" || !eventData.token || eventData.token === undefined) {
      Message("token不存在，请登录", 2, 3000);
      dbgjObj.isLogin = false;
    } else {
      localStorage.setItem("dbgjToken", eventData.token);
      dbgjObj.isLogin = true;
    }
    homeInit();
  });
}
// 弹窗根据索引选中标签
function chooseFeature(index) {
  let showTab = $(".dbgj-dialog-tabs-box .dialog-tabs").find("li[index=" + index + "]");
  showTab.addClass("selected").siblings("li").removeClass("selected");
  let showContent = $(".dbgj-dialog-tabs-box .dialog-content-box").find("#dialog-content-" + index);
  showContent.removeClass("dbgj-hide").siblings(".dialog-content").addClass("dbgj-hide");
}

// 悬浮窗口相关代码
function homeInit() {
  $('#dbgj-home .dbgj-feature-page').addClass("dbgj-hide");
  if (!dbgjObj.isLogin) {
    $("#dbgj-home .dbgj-feature-page").addClass("dbgj-hide")
    $("#dbgj-register-login-page").removeClass("dbgj-hide");
    getLoginQrCode();
  }
  loginAfterInit();
  // 收缩与展开
  $(".dbgj-home-header").on("click", ".action", function (e) {
    if ($(this).find(".header-shrink").hasClass("dbgj-hide")) {
      // 展开
      $(this).find(".header-shrink").removeClass("dbgj-hide");
      $(this).find(".header-magnify").addClass("dbgj-hide");
      $(".dbgj-home-content").stop().slideDown();
      $(".dbgj-home").removeClass("close");
    } else {
      // 收起
      $(this).find(".header-shrink").addClass("dbgj-hide");
      $(this).find(".header-magnify").removeClass("dbgj-hide");
      $(".dbgj-home-content").stop().slideUp();
      $(".dbgj-home").addClass("close");
    }
  });
  // 功能选择
  $(".dbgj-feature-btn").click(function (e) {
    // 根据索引选中tab
    
    let index = Number($(this).attr("index"));
    if (index === 1) { // 查号黑科技1
      $('.dbgj-feature-page').addClass("dbgj-hide");
      $("#dbgj-checkNo-page").removeClass("dbgj-hide");
    } else if (index === 2) { // 数据分析工具2
      $('.dbgj-feature-page').addClass("dbgj-hide");
      $("#dbgj-dataAnalysis-page").removeClass("dbgj-hide");
    } else if (index === 3) { // 详情页工具3
      $('.dbgj-feature-page').addClass("dbgj-hide");
      $("#dbgj-details-page").removeClass("dbgj-hide");
    } else if (index === 4) { // 商家助手4
      $('.dbgj-feature-page').addClass("dbgj-hide");
      $("#dbgj-merchantAssistant-page").removeClass("dbgj-hide");
    } else if (index === 5) { // 网页版黑科技5
      window.open("https://www.dabaigongju.com");
    } else if (index === 6) { // 个人中心6
      if (!dbgjObj.isLogin) {
        Message("请先登录", 3, 3000);
        $("#dbgj-home .dbgj-feature-page").addClass("dbgj-hide")
        $("#dbgj-register-login-page").removeClass("dbgj-hide");
        getLoginQrCode();
        return false;
      }
      getCurrentUserInfo();
      $('.dbgj-feature-page').addClass("dbgj-hide");
      $("#dbgj-myCentre-page").removeClass("dbgj-hide");
    } else if (index < 20 && index > 10) {
      if (!dbgjObj.isLogin) {
        Message("请先登录", 3, 3000);
        $("#dbgj-home .dbgj-feature-page").addClass("dbgj-hide")
        $("#dbgj-register-login-page").removeClass("dbgj-hide");
        getLoginQrCode();
        return false;
      }
      Dialog("查号黑科技", dbgjCheckNumHtml, 1600, 800);
      chooseFeature(index);
      checkNumInit();
    } else if (index < 30 && index > 20) {
      if (!dbgjObj.isLogin) {
        Message("请先登录", 3, 3000);
        $("#dbgj-home .dbgj-feature-page").addClass("dbgj-hide")
        $("#dbgj-register-login-page").removeClass("dbgj-hide");
        getLoginQrCode();
        return false;
      }
      Dialog("数据分析工具", dbgjDataAnalysisHtml, 1352, 700)
      chooseFeature(index);
      dataAnalysisToolInit();
    } else if (index < 40 && index > 30) {
      if (!dbgjObj.isLogin) {
        Message("请先登录", 3, 3000);
        $("#dbgj-home .dbgj-feature-page").addClass("dbgj-hide")
        $("#dbgj-register-login-page").removeClass("dbgj-hide");
        getLoginQrCode();
        return false;
      }
      Dialog("详情页工具", dbgjDetailsToolsHtml, 1352, 700)
      chooseFeature(index);
      detailsToolInit();
    } else if (index < 50 && index > 40) {
      if (!dbgjObj.isLogin) {
        Message("请先登录", 3, 3000);
        $("#dbgj-home .dbgj-feature-page").addClass("dbgj-hide")
        $("#dbgj-register-login-page").removeClass("dbgj-hide");
        getLoginQrCode();
        return false;
      }
      Dialog("商家助手工具", dbgjBusinessAssistantHtml, 1352, 700)
      chooseFeature(index);
      merchantAssistantInit();
    }
  });
  // 返回 
  $(".dbgj-footer-back, .dbgj-mycenter-footer-back").click(function (e) {
    let page = $(this).closest(".dbgj-feature-page").attr("id");
    if (page=== "dbgj-account-login-page") {
      // 账号登录页返回扫码登录注册页
      $(".dbgj-feature-page").addClass("dbgj-hide");
      $("#dbgj-register-login-page").removeClass("dbgj-hide");
      return;
    };
    if (page === "dbgj-forget-password-page") {
      // 忘记密码页返回账号登录页
      $(".dbgj-feature-page").addClass("dbgj-hide");
      $("#dbgj-account-login-page").removeClass("dbgj-hide");
      return;
    };
    if (page === "dbgj-withdraw-deposit-page") {
      // 提现页返回邀请码页
      $(".dbgj-feature-page").addClass("dbgj-hide");
      $("#dbgj-invite-code-page").removeClass("dbgj-hide");
      return;
    };
    if (page === "dbgj-invite-code-page") {
      // 邀请页返回个人中心页
      $(".dbgj-feature-page").addClass("dbgj-hide");
      $("#dbgj-myCentre-page").removeClass("dbgj-hide");
      return;
    };
    
    $(".dbgj-feature-page").addClass("dbgj-hide");
  });
  // 退出登录
  $(".dbgj-logout").click(function (e) {
    Message("退出成功");
    $("#dbgj-home .dbgj-feature-page").addClass("dbgj-hide")
    $("#dbgj-register-login-page").removeClass("dbgj-hide");
    window.postMessage({
      action: "setToken",
      value: ""
    }, "*")
    localStorage.setItem("dbgjToken", "");
    dbgjObj.isLogin = false;
    // 生成登录二维码
    getLoginQrCode();
  });
  // 重新获取登录二维码
  $("#dbgj-register-login-page .refresh-code").click(function () {
    getLoginQrCode();
  });
  // 去账号登录
  $("#dabgjAccountLogin").click(function() {
    // 获取是否记住密码
    window.addEventListener("message", function(e) {
      if (e.data.action === "getRememberPwCb") {
        if (e.data.value.userAccount) {
          const userAccount = e.data.value.userAccount;
          $("#dbgj-login-account").val(userAccount.userName);
          $("#dbgj-login-password").val(userAccount.password);
          $(this).attr("checked", userAccount.checked);
        }
      }
    });
    window.postMessage({
      action: "getRememberPw"
    }, "*");
    // 清理扫码登录定时器
    $("#dbgj-register-login-page .dbgj-login-code-box .refresh-code").removeClass("dbgj-hide").siblings(".scan-code").addClass("dbgj-hide");
    $("#dbgj-home .dbgj-feature-page").addClass("dbgj-hide")
    $("#dbgj-account-login-page").removeClass("dbgj-hide");
    if (dbgjObj.loginTimerId !== null) {
      clearTimeout(dbgjObj.loginTimerId);
    }
  });
  // 绑定手机号获取验证码
  $("#dbgj-bind-phone-page .dbgj-get-verify-code").click(function () {
    const self = $(this);
    if (self.hasClass("disabled")) return false;
    //检查是否有手机号码
    let phone = $("#dbgj-register-account").val();
    if (phone === "") {
      Message("请输入手机号码", 3, 3000);
      return;
    } else if ($.verifyPhone(phone) === false) {
      Message("请输入规范的手机号码", 3, 3000);
      return;
    }
    
    //通过以上检验，发送短信
    dbgjObj.aliPhone = phone;

    // 倒计时
    self.addClass("disabled");
    let totalTime = 60;
    let clock = window.setInterval(() => {
      totalTime--;
      self.text(totalTime + "s");
      if (totalTime <= 0) {
        window.clearInterval(clock);
        self.text("获取验证码");
        totalTime = 60;
        self.removeClass("disabled") //这里重新开启
      }
    }, 1000);
    // 获取验证码
    getAliCode(phone);
  });
  // 绑定手机确定注册
  $("#dbgj-bind-phone-page .dbgj-register-btn").click(function (e) {
    let account = $("#dbgj-register-account").val();
    let verifyCode = $("#dbgj-register-vcode").val();
    let password = $("#dbgj-register-password").val();
    let inviteCode = $("#dbgj-invite-code").val();
    let checked_protocol = $("#dbgj-check-protocol").prop("checked");
    if (!$.verifyPhone(account)) {
      Message("请输入正确格式的手机号码", 3, 3000);
      return false
    }
    if (verifyCode.length <= 0) {
      Message("请输入验证码", 3, 3000);
      return false
    }
    if (!$.verifyPassword(password)) {
      Message("请输入6-18位长度的密码（不能输入符号）", 3, 3000);
      return false
    }
    if (!checked_protocol) {
      Message("请勾选同意隐私协议", 3, 3000);
      return false
    }
    ajaxFetch("POST", dbgjBase + "/user/register", {
      userName: account,
      password: password,
      code: verifyCode,
      inviteCode: inviteCode,
      uuid: dbgjObj.uuid
    }, function (result) {
      const {
        data,
        code,
        msg
      } = result;
      if (code === "1") {
        return false;
      }
      if (code === "3") {
        Message(msg, 3, 3000);
        return false;
      }
      // 邀请码自动兑换
      ajaxFetch("GET", dbgjBase + "/convertMember?invite=" + inviteCode, null, function(res) {
      });
      Message(msg, 1, 3000);
      //设置到bg
      window.postMessage({
        action: "setToken",
        value: data.token
      }, '*');
      //设置到local
      localStorage.setItem('dbgjToken', data.token);
      dbgjObj.isLogin = true;
      $(".dbgj-feature-page").addClass("dbgj-hide");
      loginAfterInit();
    });
  });
  // 账号登录
  $("#dbgj-login-submit").click(function() {
    let account = $("#dbgj-login-account").val();
    let password = $("#dbgj-login-password").val();
    let checked = $("#dbgj-remember-password").attr("checked");
    if (!$.verifyPhone(account)) {
      Message("请输入正确格式的手机号码", 3, 3000);
      return false
    }
    if (!$.verifyPassword(password)) {
      Message("请输入6-18位长度的密码（不能输入符号）", 3, 3000);
      return false
    }
    let pwd = password;
    if (!checked) {
      pwd = ""
    }
    let userAccount = {
      userName: account,
      password: pwd,
      checked: checked
    };
    window.postMessage({
      action: "setRememberPw",
      value: userAccount
    }, '*');
    // 账号登录请求
    ajaxFetch("POST", dbgjBase + "/user/login", {userName: account, password: password}, function(res) {
      const {code, data} = res;
      if (code === "1") return;
      if (code === "0" && data !== null) {
        //设置到bg
        window.postMessage({
          action: "setToken",
          value: data.token
        }, '*');
        //设置到local
        localStorage.setItem('dbgjToken', data.token);
        clearTimeout(dbgjObj.loginTimerId);
        dbgjObj.isLogin = true;
        Message("登录成功");
        $("#dbgj-account-login-page").addClass("dbgj-hide");
        loginAfterInit();
      }
    });
  });
  // 记住密码
  $("#dbgj-remember-password").change(function() {
    let checked = $(this).attr("checked");
    let account = $("#dbgj-login-account").val();
    let password = $("#dbgj-login-password").val();
    if (!checked) {
      password = ""
    }
    let userAccount = {
      userName: account,
      password: password,
      checked: checked
    };
    window.postMessage({
      action: "setRememberPw",
      value: userAccount
    }, '*');
  });
  // 去忘记密码
  $("#to-dbgj-forget-password").click(function() {
    $("#dbgj-home .dbgj-feature-page").addClass("dbgj-hide")
    $("#dbgj-forget-password-page").removeClass("dbgj-hide");
  });
  // 忘记密码获取验证码
  $("#dbgj-forget-password-page .dbgj-get-verify-code").click(function () {
    const self = $(this);
    if (self.hasClass("disabled")) return false;
    //检查是否有手机号码
    let phone = $("#dbgj-forget-account").val();
    if (phone === "") {
      Message("请输入手机号码", 3, 3000);
      return;
    } else if ($.verifyPhone(phone) === false) {
      Message("请输入规范的手机号码", 3, 3000);
      return;
    }
    //通过以上检验，发送短信
    dbgjObj.aliPhone = phone;

    // 倒计时
    self.addClass("disabled");
    let totalTime = 60;
    let clock = window.setInterval(() => {
      totalTime--;
      self.text(totalTime + "s");
      if (totalTime <= 0) {
        window.clearInterval(clock);
        self.text("获取验证码");
        totalTime = 60;
        self.removeClass("disabled") //这里重新开启
      }
    }, 1000);
    // 获取验证码
    getAliCode(phone);
  });
  // 新密码提交
  $("#dbgj-forget-password-submit").click(function() {
    let account = $("#dbgj-forget-account").val();
    let verifyCode = $("#dbgj-forget-vcode").val();
    let password = $("#dbgj-forget-password").val();
    if (!$.verifyPhone(account)) {
      Message("请输入正确格式的手机号码", 3, 3000);
      return false
    }
    if (verifyCode.length <= 0) {
      Message("请输入验证码", 3, 3000);
      return false
    }
    if (!$.verifyPassword(password)) {
      Message("请输入6-18位长度的密码（不能输入符号）", 3, 3000);
      return false
    }
    // 忘记密码请求
    ajaxFetch("POST", dbgjBase + "/user/forgetPwd", {mobile: account, password: password, code: verifyCode}, function(res) {
      const { data, code, msg } = res
        if (code === "-1") {
          Message(msg, 3, 3000);
          return;
        }
        //设置到bg
        window.postMessage({
          action: "setToken",
          value: data.token
        }, '*');
        //设置到local
        localStorage.setItem('dbgjToken', data.token);
        clearTimeout(dbgjObj.loginTimerId);
        dbgjObj.isLogin = true;
        Message("登录成功");
        $("#dbgj-forget-password-page").addClass("dbgj-hide");
        loginAfterInit();
    });
  })
  // 充值金币
  $(".dbgj-recharge-page .coin-recharge-btn").click(function (e) {
    $(".dbgj-recharge-page .gold-coin-list-box").removeClass("dbgj-hide");
    $(".dbgj-recharge-page .permission-list-box").addClass("dbgj-hide");
    $(".dbgj-recharge-page .group-buy-box").addClass("dbgj-hide");
    $(".dbgj-recharge-page .coin-pay-box").addClass("dbgj-hide");
    if (dbgjObj.getPayStatusTimeId) {
      clearTimeout(dbgjObj.getPayStatusTimeId);
    }
  });
  // 返回权限列表
  $(".dbgj-recharge-page .back-permission-list").click(function () {
    $(".dbgj-recharge-page .coin-pay-box").addClass("dbgj-hide");
    $(".dbgj-recharge-page .group-buy-box").addClass("dbgj-hide");
    $(".dbgj-recharge-page .gold-coin-list-box").addClass("dbgj-hide");
    $(".dbgj-recharge-page .permission-list-box").removeClass("dbgj-hide");
    if (dbgjObj.getPayStatusTimeId) {
      clearTimeout(dbgjObj.getPayStatusTimeId);
    }
  });
  // 选择单人/拼团购买
  $(".buy-way-box .buy-way").click(function () {
    $(this).addClass("selected");
    $(this).siblings(".buy-way").removeClass("selected");
  });
  // 选择权限套餐
  $(".permission-list-box .buy-item .type").click(function () {
    $(this).addClass("selected");
    $(this).closest(".buy-item").siblings(".buy-item").find(".type").removeClass("selected");
  });
  // 选择金币套餐
  $(".gold-coin-list-box .buy-item .type").click(function () {
    $(this).addClass("selected");
    $(this).closest(".buy-item").siblings(".buy-item").find(".type").removeClass("selected");
  });
  // 个人中心充值按钮展开充值页面
  $("#dbgj-myCentre-page .my-center-info .recharge").click(function () {
    $(".dbgj-recharge-page").slideDown();
    getCurrentUserInfo(function() {
      // 当前会员等级
      let level = dbgjObj.currentUserInfo.vipLevel;
      if (level == "0") {
        $(".dbgj-recharge-page").find(".vipLevel").text("游客");
      } else if(level == "1") {
        $(".dbgj-recharge-page").find(".vipLevel").text("基础版");
      } else if (level == "2") {
        $(".dbgj-recharge-page").find(".vipLevel").text("豪华版");
      } else if (level == "3") {
        $(".dbgj-recharge-page").find(".vipLevel").text("尊贵版");
      }
      let endTime = dbgjObj.currentUserInfo.endTime;
      if (endTime === null) {
        $(".dbgj-recharge-page").find(".endTime").text("无");
      } else {
        $(".dbgj-recharge-page").find(".endTime").text(dbgjObj.timestampToDate(endTime));
      }
      let goldCoin = dbgjObj.currentUserInfo.goldCoin;
      $(".dbgj-recharge-page").find(".goldCoin").text(goldCoin);
    });
  });
  // 关闭充值页面
  $(".dbgj-recharge-page .close").click(function () {
    $(".dbgj-recharge-page").slideUp();
    if (dbgjObj.getPayStatusTimeId !== null) {
      clearTimeout(dbgjObj.getPayStatusTimeId);
    }
  });
  // 立即充值金币
  $(".gold-coin-list-box .recharge-now").click(function () {
    function getPayCoinsOrder(money, cardType) {
      if (dbgjObj.getPayStatusTimeId !== null) {
        clearTimeout(dbgjObj.getPayStatusTimeId);
      }
      ajaxFetch("get", `${dbgjBase}/getJsPayQrcode?money=${money}&cardType=${cardType}`, null , function(res) {
        const { code, data, msg } = res;
        if (code === "1") {
          setTimeout(() => {
            getPayCoinsOrder(money, cardType);
          }, 300);
        }
        let outTradeNo = data.outTradeNo;
        let qrSrc = data.qrSrc;
        $("#dbgj-goldCoin-qrcode").empty();
          $("#dbgj-goldCoin-qrcode").qrcode({
            width: 160,
            height: 160,
            text: qrSrc
          });
          getPayCoinsStatus(outTradeNo);
      });
      function getPayCoinsStatus(outTradeNo) {
        ajaxFetch("GET", dbgjBase + "/payjs/getOrder?outTradeNo="+ outTradeNo, null, function(res) {
          const {code, bizStatus, data, msg} = res;
          if (bizStatus == "-1") {
           dbgjObj.getPayStatusTimeId = setTimeout(() => {
            getPayCoinsStatus(outTradeNo);
            }, 2000);
          }
          // 支付失败
          if (bizStatus == "2") {
            Message(msg, 3, 4000);
            clearTimeout(dbgjObj.getPayStatusTimeId);
            return;
          }
          // 支付成功
          if (bizStatus == "1") {
            Message(msg, 1, 4000);
            clearTimeout(dbgjObj.getPayStatusTimeId);
            getCurrentUserInfo(function() {
              $(".dbgj-recharge-page .gold-coin-list-box").removeClass("dbgj-hide");
              $(".dbgj-recharge-page .coin-pay-box").addClass("dbgj-hide");
              // 当前会员等级
              let level = dbgjObj.currentUserInfo.vipLevel;
              if (level == "0") {
                $(".dbgj-recharge-page").find(".vipLevel").text("游客");
              } else if (level == "1") {
                $(".dbgj-recharge-page").find(".vipLevel").text("基础版");
              } else if (level == "2") {
                $(".dbgj-recharge-page").find(".vipLevel").text("豪华版");
              } else if (level == "3") {
                $(".dbgj-recharge-page").find(".vipLevel").text("尊贵版");
              }
              let endTime = dbgjObj.currentUserInfo.endTime;
              if (endTime === null) {
                $(".dbgj-recharge-page").find(".endTime").text("无");
              } else {
                $(".dbgj-recharge-page").find(".endTime").text(dbgjObj.timestampToDate(endTime));
              }
              let goldCoin = dbgjObj.currentUserInfo.goldCoin;
              $(".dbgj-recharge-page").find(".goldCoin").text(goldCoin);
            });
          }
        });
      }
    }
    let coinType = $(this).siblings(".buy-item").find(".type.selected").attr("data-coin");
    let coinMoney = $(this).siblings(".buy-item").find(".type.selected").attr("data-money");
    let coinText = $(this).siblings(".buy-item").find(".type.selected").attr("data-text");
    $(".dbgj-recharge-page .gold-coin-list-box").addClass("dbgj-hide");
    $(".dbgj-recharge-page .coin-pay-box").removeClass("dbgj-hide");
    $(".dbgj-recharge-page .coin-pay-box .coins-version").text(coinText);
    $(".dbgj-recharge-page .coin-pay-box .coins-blance").text(coinMoney + "元");
    getPayCoinsOrder(coinMoney, coinType);
  });
  // 购买权限
  $(".permission-list-box .recharge-now").click(function () {
    function getPayCode(money, cardType) {
      if (dbgjObj.getPayStatusTimeId !== null) {
        clearTimeout(dbgjObj.getPayStatusTimeId);
      }
      ajaxFetch("GET", `${dbgjBase}/getJsPayQrcode?money=${money}&cardType=${cardType}`, null ,function(res) {
        const { code, data, msg } = res;
        if (code === "1") {
          setTimeout(() => {
            getPayCode(money, cardType)
          }, 300);
        }
        let outTradeNo = data.outTradeNo;
        let qrSrc = data.qrSrc;
        $("#dbgj-permission-qrcode").empty();
          $("#dbgj-permission-qrcode").qrcode({
            width: 160,
            height: 160,
            text: qrSrc
          });
        getPayStatus(outTradeNo);
      });
      function getPayStatus(outTradeNo) {
        ajaxFetch("GET", dbgjBase + "/payjs/getOrder?outTradeNo="+ outTradeNo, null, function(res) {
          const {code, bizStatus, data, msg} = res;
          if (bizStatus == "-1") {
           dbgjObj.getPayStatusTimeId = setTimeout(() => {
              getPayStatus(outTradeNo);
            }, 2000);
          }
          // 支付失败
          if (bizStatus == "2") {
            Message(msg, 3, 4000);
            clearTimeout(dbgjObj.getPayStatusTimeId);
            return;
          }
          // 支付成功
          if (bizStatus == "1") {
            Message(msg, 1, 4000);
            clearTimeout(dbgjObj.getPayStatusTimeId);
            getCurrentUserInfo(function() {
              $(".dbgj-recharge-page .permission-list-box").removeClass("dbgj-hide");
              $(".dbgj-recharge-page .group-buy-box").addClass("dbgj-hide");
              // 当前会员等级
              let level = dbgjObj.currentUserInfo.vipLevel;
              if (level == "0") {
                $(".dbgj-recharge-page").find(".vipLevel").text("游客");
              } else if (level == "1") {
                $(".dbgj-recharge-page").find(".vipLevel").text("基础版");
              } else if (level == "2") {
                $(".dbgj-recharge-page").find(".vipLevel").text("豪华版");
              } else if (level == "3") {
                $(".dbgj-recharge-page").find(".vipLevel").text("尊贵版");
              }
              let endTime = dbgjObj.currentUserInfo.endTime;
              if (endTime === null) {
                $(".dbgj-recharge-page").find(".endTime").text("无");
              } else {
                $(".dbgj-recharge-page").find(".endTime").text(dbgjObj.timestampToDate(endTime));
              }
              let goldCoin = dbgjObj.currentUserInfo.goldCoin;
              $(".dbgj-recharge-page").find(".goldCoin").text(goldCoin);
            });
          }
        });
      }
    }
    let permissionText = $(this).siblings(".buy-item").find(".type.selected").attr("data-text");
    let permissionType = $(this).siblings(".buy-item").find(".type.selected").attr("data-per");
    let permissionMoney = $(this).siblings(".buy-item").find(".type.selected").attr("data-money");
    let buyWay = $(this).siblings(".buy-way-box").find(".buy-way.selected").attr("data-way");
    $(".dbgj-recharge-page .permission-list-box").addClass("dbgj-hide");
    $(".dbgj-recharge-page .group-buy-box").removeClass("dbgj-hide");
    $(".dbgj-recharge-page .coin-pay-box").addClass("dbgj-hide");
    
    if (buyWay === "way1") {
      $(".dbgj-recharge-page .group-buy-box .title").text("立即购买");
      $(".dbgj-recharge-page .group-buy-box .group-buy-msg").addClass("dbgj-hide");
    } 
    // else {
    //   $(".dbgj-recharge-page .group-buy-box .title").text("两人拼团");
    //   $(".dbgj-recharge-page .group-buy-box .group-buy-msg").removeClass("dbgj-hide");
    // }
    $(".dbgj-recharge-page .group-buy-box .permission-version").text(permissionText);
    $(".dbgj-recharge-page .group-buy-box .valid-until").text(permissionMoney+"元");
    getPayCode(permissionMoney, permissionType);
  });
  // 套餐说明
  $(".dbgj-recharge-page .explain, .dbgj-recharge-page .coin-explain").click(function() {
    Dialog("套餐说明", dbgjPurchaseDescriptionHtml, 1500, 700, true);
    // 获取iframe里面的window对象
    // var frameWidow = document.getElementById('iframe').contentWindow;
    // 然后监听scroll事件
    $(".dbgj-purchase-description-table-box").scroll(function(){
      if ($(this).scrollTop() > 100) {
        $(".head_table.dbgj-purchase-description-table").show();
      } else {
        $(".head_table.dbgj-purchase-description-table").hide();
      }
    });
  });
  // 返回购买金币页面
  $(".back-coin-list").click(function() {
    $(".dbgj-recharge-page .gold-coin-list-box").removeClass("dbgj-hide");
    $(".dbgj-recharge-page .coin-pay-box").addClass("dbgj-hide");
  });
  // 去邀请链接
  $("#toInviteFriendPage").click(function() {
    $(".dbgj-feature-page").addClass("dbgj-hide");
    $("#dbgj-invite-code-page").removeClass("dbgj-hide");
    // 获取邀请码和邀请链接
    ajaxFetch("GET", dbgjBase + "/userInvite/getInviteCode", null , function(res) {
      const {code, data} = res;
      if (code === "1") return;
      if (code === "0") {
        $("#dbgj_invite_link").val(data.inviteUrl);
        $("#dbgj_invite_code").val(data.inviteCode);
        $("#dbgj_invite_code_copy").attr("data-clipboard-text", data.inviteCode);
        $("#dbgj_invite_link_copy").attr("data-clipboard-text", data.inviteUrl);
       // 获取邀请码奖励请求
        ajaxFetch("GET", dbgjBase + "/inviteInfo?invite="+ data.inviteCode, null, function(result) {
          const {code, data} = result;
          if (code === "1") return;
          if (code === "0") {
            $("#invite_award_days").text(data.rewardays);
            $("#invite_award_aready").text(data.inviteCount);
            $("#invite_award_cash").text(data.cash);
          }
        })
      }
    });
    
  });
  //复制子链接
  $('#dbgj_invite_link_copy').click(function (event) {
    var clipboard = new Clipboard('#dbgj_invite_link_copy');
    clipboard.on("success", function (e) {
        // 复制成功
        // layer.open({
        //     title: 'dianshangdanao.com',
        //     content: '免登录共享链接已生成，粘贴分享给您的好友，好友可以直接打开链接进行使用，无需登录账号密码，24小时有效'
        // });
        Message("复制成功");
        e.clearSelection();
        clipboard.destroy();
    });
    clipboard.on("error", function (e) {
        //复制失败；
        console.log(e.action)
    });
    clipboard.onClick(event)
  });
  //复制邀请码
  $('#dbgj_invite_code_copy').click(function (event) {
    var clipboard = new Clipboard('#dbgj_invite_code_copy');
    clipboard.on("success", function (e) {
        // 复制成功
        // layer.open({
        //     title: 'dianshangdanao.com',
        //     content: '免登录共享链接已生成，粘贴分享给您的好友，好友可以直接打开链接进行使用，无需登录账号密码，24小时有效'
        // });
        Message("复制成功");
        e.clearSelection();
        clipboard.destroy();
    });
    clipboard.on("error", function (e) {
        //复制失败；
        console.log(e.action)
    });
    clipboard.onClick(event)
  });
  //复制邀请链接
  $('#dbgj_invite_link_copy').click(function (event) {
    var clipboard = new Clipboard('#dbgj_invite_link_copy');
    clipboard.on("success", function (e) {
        // 复制成功
        // layer.open({
        //     title: 'dianshangdanao.com',
        //     content: '免登录共享链接已生成，粘贴分享给您的好友，好友可以直接打开链接进行使用，无需登录账号密码，24小时有效'
        // });
        Message("复制成功");
        e.clearSelection();
        clipboard.destroy();
    });
    clipboard.on("error", function (e) {
        //复制失败；
        console.log(e.action)
    });
    clipboard.onClick(event)
  });
  // 兑换邀请码
  $("#dbgj_redeem_code").click(function() {
    let ownInviteCode = $("#dbgj_invite_code").val();
    let inviteCode = $("#dbgj_redeem_code_input").val();
    if (ownInviteCode == inviteCode) {
      MessageBox("兑换码", "不能使用自己的邀请码,可通过好友分享获得邀请码");
      return;
    }
    if ($.isEmpty(inviteCode)) {
      Message("请先填写兑换码", 3, 3000);
      return;
    }
    // 兑换邀请码请求
    ajaxFetch("GET", dbgjBase + "/convertMember?invite=" + inviteCode, null, function(res) {
      const { code, msg, data } = res;
      if (code === "0") {
        Message("兑换成功");
        getCurrentUserInfo();
      }
    });
  });
  // 邀请规则
  $("#dbgj_invite_rules").click(function() {
    let html = `<div>
    <p style="margin-bottom:5px">1.复制你的个人链接或邀请码让好友注册，好友注册后成功绑定微信并下载插件后，您可获得7天会员奖励，好友也可获得7天会员体验，每个人最多可邀请10个好友注册，相当于最多可获得70天奖励。</p>
    <p style="margin-bottom:5px">2.如果您是会员，则在原基础的会员上延长7天。</p>
    <p style="margin-bottom:5px">3.好友通过您的邀请充值后，您可获得10%的现金奖励，满100元可提现。</p>
    <p style="margin-bottom:5px">4.通过不正当的手段获得奖励，大白工具有权撤销奖励。</p>
  </div>`
    MessageBox("邀请规则", html);
  });
  // 去提现金额页面
  $("#to_withdraw_deposit_page").click(function() {
    window.open("https://www.dabaigongju.com/views/invite/invite.html");
    // $(".dbgj-feature-page").addClass("dbgj-hide");
    // $("#dbgj-withdraw-deposit-page").removeClass("dbgj-hide");
    // let cash = $("#invite_award_cash").text();
    // $("#withdraw_deposit_account_cash").text(cash);
  });
  // 获取提现验证码
  $("#get_withdraw_deposit_code").click(function() {
    const self = $(this);
    let phone = dbgjObj.currentUserInfo.userName;
    let msgHtml = `<p>是否向你绑定的手机号<span style="color:rgba(255,61,51,1)">${phone}</span>发送验证码</p>`;
    layer.confirm(msgHtml, {
      title: false, //不显示标题
      skin: "layui-layer-btn-red",
      btn: [ '确定'] //按钮
    }, function(){
      layer.closeAll(); //疯狂模式，关闭所有层
      //通过以上检验，发送短信
      dbgjObj.aliPhone = phone;
      // 倒计时
      self.addClass("disabled");
      let totalTime = 60;
      let clock = window.setInterval(() => {
        totalTime--;
        self.text(totalTime + "s");
        if (totalTime <= 0) {
          window.clearInterval(clock);
          self.text("获取验证码");
          totalTime = 60;
          self.removeClass("disabled") //这里重新开启
        }
      }, 1000);
      // 获取验证码
      getAliCode(phone);
    });
  })
  // 确定提现
  $("#confirm_withdraw_deposit").click(function() {
   let cash = $("#withdraw_deposit_account_cash").text();
   let acount = $("#withdraw_deposit_account").val();
   let name = $("#withdraw_deposit_name").val();
   let code = $("#withdraw_deposit_code").val();
   let money =  $("#withdraw_deposit_money").val();
   if (Number(cash) <= 0) {
     Message("你没有可以提现的金额额度", 3, 4000);
     return;
   }
   if (money < 100) {
     Message("提现金额最低100元起", 3, 3000);
     return;
   }
   if ($.isEmpty(acount)) {
    Message("请先填写支付宝账号", 3, 3000);
   }
   if ($.isEmpty(name)) {
    Message("请先填写支付宝实名", 3, 3000);
    return;
  }
   if ($.isEmpty(code)) {
     Message("请先获取验证码", 3, 3000);
     return;
   }
  //  提现请求
   ajaxFetch("POST", dbgjBase +　"", {}, function(res) {

   })
  });

  // 详情页展示用户信息
  $("#detailPageShowUserInfo").click(function() {
    ////询问框
    getCurrentUserInfo(function() {
      let level = dbgjObj.currentUserInfo.vipLevel;
      let vipText = level == "1" ? "基础版" : level == "2" ? "豪华版" : level == "3" ? "尊贵版" : "游客"
      let endTime = dbgjObj.currentUserInfo.endTime ? dbgjObj.timestampToDate(dbgjObj.currentUserInfo.endTime) : "无"
      let html = `<div class="dbgj-info-popup-box">
        <div class="dbgj-mt-10 dbgj-mb-10"><span>账号：</span><span class="userName">${dbgjObj.currentUserInfo.userName}</span></div>
        <table class="check-black-info-table">
          <thead>
            <tr>
              <th class="dbgj-font-gray dbgj-t-center">产品名称</th>
              <th class="dbgj-font-gray dbgj-t-center">过期时间</th>
              <th class="dbgj-font-gray dbgj-t-center">续费链接</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td class="dbgj-font-gray dbgj-fontw dbgj-t-center vipLevel">${vipText}</td>
              <td class="dbgj-font-gray dbgj-fontw dbgj-t-center endTime">${endTime}</td>
              <td class="dbgj-font-gray dbgj-t-center"><span class="dbgj-warn-btn toRenewalPlan">
              <a href="https://www.dabaigongju.com/views/pay/pay.html" target="_blank" style="color:#fff;text-decoration:none">点击续费</a></span></td>
            </tr>
          </tbody>
        </table>
        <div class="dbgj-mt-10"><span>使用帮助：</span><span class="dbgj-warn-btn userHelp">
          <a href="https://www.dabaigongju.com/views/tutorial/tutorial.html" target="_blank" style="color:#fff;text-decoration:none">点击查看</a></span></div>
        <div class="dbgj-mt-10"><span>客服帮助：</span><span class="dbgj-warn-btn serviceHelp" style="position:relative">联系客服
          <div class="dbgj-hover-code" style="left: -25px;width:138px">
            <img class="dbgj-img" src="https://upload.dabaigongju.com/202003171453305305.png" alt="扫码添加客服">
            <h2>扫码添加客服</h2>
            <span class="arrow" style="margin-left:56px"></span>
          </div>
        </span></div>
        <div class="dbgj-mt-10"><span>赚免费会员：</span><span class="dbgj-warn-btn inviteFreeVip">
          <a href="https://www.dabaigongju.com/views/user/user.html" target="_blank" style="color:#fff;text-decoration:none">邀请好友享免费会员</a></span></div>
      </div>`;
      layer.confirm(html, {
        title: false, //不显示标题
        skin: "layui-layer-btn-red",
        btn: ['关闭'] //按钮
      }, function(){
        layer.closeAll(); //疯狂模式，关闭所有层
      });
    })
  });
  $("#categoryTypeTips").on("mouseenter", function() {
    //小tips
    let text = $(this).data("tips"); 
    layer.tips(text, '#categoryTypeTips', {
      tips: [3, '#FF3D33'],
      time: 4000
    });
  });
  $("#categoryTypeTips").on("mouseleave", function() {
    //小tips
    layer.tips({
      time: 0
    });
  });

  // 后台订单列表
  // 获取当前页的全部旺旺列表
  $("#dbgjCheckAllWw").click(function() {
    let wwArr = [];
     $(".dbgjSellerBox").each(function() {
      wwArr.push($(this).data("wangwang"));
    });
    function checkWw(index) {
      if (index === wwArr.length) {
        getCurrentUserInfo();
        return;
      };
      let ww = wwArr[index];
      $('.dbgjSellerBox[data-wangwang="'+ ww +'"]').find(".dbgjCheckWwResult").removeClass("dbgj-hide").html("黑号查询中...");
      $.ajax({
        type: "GET",
        url: dbgjBase + "/checkNick?wangwang=" + encodeURIComponent(ww),
        data: null,
        dataType: 'json',
        contentType: "application/json;charset=UTF-8",
        headers: {
          "token": localStorage.getItem("dbgjToken") ? localStorage.getItem("dbgjToken") : "",
        },
        success: function (res) {
          const {
            code,
            msg,
            data
          } = res;
          if (code === "201" || code === "202") {
            dbgjObj.isLogin = false;
            Message(msg, 3, 3000);
            layer.closeAll();
            $("#dbgj-home .dbgj-feature-page").addClass("dbgj-hide")
            $("#dbgj-register-login-page").removeClass("dbgj-hide");
            $("#dbgj-register-login-page .dbgj-login-code-box .refresh-code").removeClass("dbgj-hide").siblings(".scan-code").addClass("dbgj-hide");
            return false;
          }
          if (code === "1") {
            $('.dbgjSellerBox[data-wangwang="'+ ww +'"]').find(".dbgjCheckWwResult").removeClass("dbgj-hide").html("查询失败，请稍等片刻再进行查询");
          }
          if (code === "0" && data.isOk) {
            let foxClassName = Number(data.fox) > 0 ? "dbgj-font-red" : "";
            let jiangNumClassName = Number(data.jiangNum) > 0 ? "dbgj-font-red" : "";
            let html = `<span>降权:</span><span class="${jiangNumClassName}">${data.jiangNum}</span><span class="dbgj-ml-10 ${foxClassName}">狐狸:</span><span>${data.fox}</span>`
            $('.dbgjSellerBox[data-wangwang="'+ ww +'"]').find(".dbgjCheckWwResult").removeClass("dbgj-hide").html(html);
          }
          setTimeout(() => {
            index++;
            checkWw(index);
          }, 100);
        },
        eror: function (err) {
          $('.dbgjSellerBox[data-wangwang="'+ ww +'"]').find(".dbgjCheckWwResult").removeClass("dbgj-hide").html("查询失败，请稍等片刻再进行查询");
          setTimeout(() => {
            index++;
            checkWw(index);
          }, 100);
        }
      });
    }
    checkWw(0);
  });
  // 单个点击查询淘客
  $(".dbgjTaokeCheck").click(function() {
    let orderNo = $(this).closest(".dbgjSellerBox").attr("data-order");
    let bhtml = `<span class="">淘客查询中...</span>`;
    $('.dbgjSellerBox[data-order="'+ orderNo +'"]').find(".dbgjCheckTkResult").removeClass("dbgj-hide").html(bhtml);
    $.ajax({
      type: "POST",
      url: dbgjBase + "/taoke/flag",
      data: JSON.stringify({orderNo: orderNo}),
      dataType: 'json',
      contentType: "application/json;charset=UTF-8",
      headers: {
        "token": localStorage.getItem("dbgjToken") ? localStorage.getItem("dbgjToken") : "",
      },
      success: function (res) {
        const {
          code,
          data
        } = res;
        if (code === "1") {
          $('.dbgjSellerBox[data-order="'+ orderNo +'"]').find(".dbgjCheckTkResult").removeClass("dbgj-hide").html("查询失败，请稍等片刻再进行查询");
        }
        getCurrentUserInfo();
        if (data.isTaoke === 0 || data.isTaoke === '0') {
          let html = `<span class="dbgj-font-orange">非淘客订单</span>`;
          $('.dbgjSellerBox[data-order="'+ orderNo +'"]').find(".dbgjCheckTkResult").removeClass("dbgj-hide").html(html);
        } else if (data.isTaoke === null) {
          $('.dbgjSellerBox[data-order="'+ orderNo +'"]').find(".dbgjCheckTkResult").removeClass("dbgj-hide").html("查询失败，请稍等片刻再进行查询");
        } else if (data.isTaoke === 1 || data.isTaoke === '1') {
          let html = `<span class="dbgj-font-red">淘客订单</span>`;
          $('.dbgjSellerBox[data-order="'+ orderNo +'"]').find(".dbgjCheckTkResult").removeClass("dbgj-hide").html(html);
        }
      },
      eror: function (err) {
        $('.dbgjSellerBox[data-order="'+ orderNo +'"]').find(".dbgjCheckTkResult").removeClass("dbgj-hide").html("查询失败，请稍等片刻再进行查询");
      }
    });
  });
  // 单个点击查黑号
  $(".dbgjCheckOneWw").click(function () {
    let autoCheckWw = $(this).closest(".dbgjSellerBox").attr("data-wangwang");
    if (!dbgjObj.isLogin) {
      Message("请先登录", 3, 3000);
      $("#dbgj-home .dbgj-feature-page").addClass("dbgj-hide")
      $("#dbgj-register-login-page").removeClass("dbgj-hide");
      getLoginQrCode();
      return false;
    }
    Dialog("查号黑科技", dbgjCheckNumHtml, 1352, 700);
    chooseFeature(11);
    checkNumInit(autoCheckWw);
  });
  // 我的个人中心
  $("#myDbgjCenter").click(function() {
    if (!dbgjObj.isLogin) {
      Message("请先登录", 3, 3000);
      $("#dbgj-home .dbgj-feature-page").addClass("dbgj-hide")
      $("#dbgj-register-login-page").removeClass("dbgj-hide");
      getLoginQrCode();
      return false;
    }
    getCurrentUserInfo();
    $('.dbgj-feature-page').addClass("dbgj-hide");
    $("#dbgj-myCentre-page").removeClass("dbgj-hide");
  });

  // 详情页获取竞品分析按钮
  $("#detailPageProductInfo").click(function() {
    if (!dbgjObj.isLogin) {
      Message("请先登录", 3, 3000);
      $("#dbgj-home .dbgj-feature-page").addClass("dbgj-hide")
      $("#dbgj-register-login-page").removeClass("dbgj-hide");
      return false;
    }
    let pid = dbgjObj.getCurrentPageId();
    // 30天的
    ajaxFetch("POST", dbgjBase + '/remoteGainAnalysis/product', {dateType: "3", productId: pid}, function (res) {
      dbgjObj.loadingClose();
      if (res.code === "1") return;
      if (res.code === '0') {
        let data = res.data;
        //表格汇总
        let sum_uvIndex = 0; //7天总买家 
        let sum_payByrCntIndex = 0; //7天总买家
        let sum_tradeIndex = 0; // 7天总金额
        let sum_payRateIndex = 0; // 7天平均转化率
        let sum_keda = 0; //7天平均客单价
        let sum_uvjz = 0; // 7天平均UV价值
        for(let i in data) {
          let item = data[i];
          sum_uvIndex = sum_uvIndex + parseFloat(item.uvIndex.replace(/,/g, ""));
          sum_payByrCntIndex = sum_payByrCntIndex + parseFloat(item.payByrCntIndex.replace(/,/g, ""));
          sum_tradeIndex = sum_tradeIndex + parseFloat(item.tradeIndex.replace(/,/g, ""));
          sum_payRateIndex = sum_payRateIndex + parseFloat(item.payRateIndex.replace(/,/g, ""));
          sum_keda = sum_keda + parseFloat(item.keda.replace(/,/g, ""));
          sum_uvjz = sum_uvjz + parseFloat(item.uvjz.replace(/,/g, ""));
        }
        let sumItem = $("#topBarSumItem");
        // sumItem.find('.sum_uvIndex').text(sum_uvIndex);
        sumItem.find('.payByrCntIndex').text(sum_payByrCntIndex);
        sumItem.find('.tradeIndex').text(sum_tradeIndex);
        sumItem.find('.payRateIndex').text(parseFloat(sum_payRateIndex / data.length).toFixed(2) + '%');
        sumItem.find('.keda').text(parseFloat(sum_keda / data.length).toFixed(2));
        sumItem.find('.uvjz').text(parseFloat(sum_uvjz / data.length).toFixed(2));
      } else {
        MessageBox("竞品分析", res.msg);
      }
    });
    // 获取昨天销量
    let date = new Date(); //实例一个时间对象；
    let year = date.getFullYear(); //获取系统的年；
    let month = date.getMonth() + 1; //获取系统月份，由于月份是从0开始计算，所以要加1
    let day = date.getDate() - 1; // 获取昨日
    if (month < 10) {
      month = "0" + month;
    }
    if (day < 10) {
      day = "0" + day
    }
    let yesterday = year + "-" + month + "-" + day;
    ajaxFetch("POST", dbgjBase + '/remoteGainAnalysis/product', {dateType: "4", dateRange: yesterday, productId: pid}, function (res) {
      if (res.code === "1") return;
      if (res.code === '0') {
        let data = res.data;
        let y_payByrCntIndex = parseFloat(data[0].payByrCntIndex.replace(/,/g, ""));
        $("#topBarSumItem").find(".y_payByrCntIndex").text(y_payByrCntIndex);
      }
    });
  })
  // 详情页工具栏1
  $(".dbgj-product-details-tool1 .dbgj-primary-btn").click(function () {
    if (!dbgjObj.isLogin) {
      Message("请先登录", 3, 3000);
      $("#dbgj-home .dbgj-feature-page").addClass("dbgj-hide")
      $("#dbgj-register-login-page").removeClass("dbgj-hide");
      return false;
    }
    let index = $(this).attr("index");
    if (index == 1) {
      // 宝贝透视（竞品分析）
      
      Dialog("数据分析工具", dbgjDataAnalysisHtml, 1352, 700)
      chooseFeature(21);
      dataAnalysisToolInit(21);
    }
    if (index == 2) {
      // 一键报表
      Dialog("一键报表", dbgjOneKeyStatementsHtml, 1352, 700);
      onekeyStatementInit();
    }
  });
}

// 查号黑科技
function checkNumInit(autoCheckWw) {
  // 标签玩法
  $("#dbgj-label-play").click(function () {
    //tab层
    let checkdetal_box = $('#checkdetal_box').html();
    let checkfun_box = $('#checkfun_box').html();

    layer.tab({
      skin: 'checkdilog-class',
      area: ['400px', '370px'],
      tab: [{
        title: '功能描述',
        content: checkdetal_box
      }, {
        title: '功能逻辑',
        content: checkfun_box
      }]
    })
    // 		layer.alert('该功能正在升级算法中，请耐心等候更新！2020年1月16日');
    // 		return;
  });
  // 验号搜索
  $("#dialog-content-11 .dbgj-search-form .search-btn").click(function () {
    if (autoCheckWw) {
      $("#checkNum_input").val(autoCheckWw);
    }
    let ww = $("#checkNum_input").val();
    if (ww.length <= 0) {
      Message("请输入旺旺号", 3, 3000);
      return;
    }
    if (ww.match(/^[^ ]+$/) === null) {
      Message("旺旺不能带有空格", 3, 3000);
      return;
    }
    if (ww.match(/'|&/)) {
      Message("旺旺带有非法字符", 3, 3000);
      return;
    }
    if (ww.match("^.{2,25}$") === null) {
      Message("旺旺为2-25长度", 3, 3000);
      return;
    }
    dbgjObj.loadingOpen();

    // 查旺旺请求
    ajaxFetch("GET", dbgjBase + "/checkNick?wangwang=" + encodeURIComponent(ww), null, function (res) {
      dbgjObj.loadingClose();
      const {
        data,
        code,
        msg
      } = res;
      getCurrentUserInfo();
      if (code === "1") {
        if(autoCheckWw) {
          $('.dbgjSellerBox[data-wangwang="'+ ww +'"]').find(".dbgjCheckWwResult").removeClass("dbgj-hide").html("查询失败，请稍等片刻再进行查询");
        }
        return false;
      }
      if (code === "2") {
        if(autoCheckWw) {
          $('.dbgjSellerBox[data-wangwang="'+ ww +'"]').find(".dbgjCheckWwResult").removeClass("dbgj-hide").html("查询失败，请稍等片刻再进行查询");
        } else {
          Message(msg, 3, 2000);
        }
        return;
      }
      if (code === "0" && data.isOk === false) {
        if(autoCheckWw) {
          $('.dbgjSellerBox[data-wangwang="'+ ww +'"]').find(".dbgjCheckWwResult").removeClass("dbgj-hide").html("查询失败，请稍等片刻再进行查询");
        } else {
          Message(data.msg, 3, 2000);
        }
        return false;
      }
      for (let key in data) {
        if (key === "purchaseRecords") {
          // 购买记录
          let idArr = ["first", "second", "third", "fouth"];
          if (data[key].length === 0) {
            for (let i in idArr) {
              if (i == 0) {
                $("#dialog-content-11 #checkNum_first_date").text("暂无数据");
                $("#dialog-content-11 #checkNum_first_count").text("暂无数据");
              } else {
                $("#dialog-content-11 #checkNum_" + idArr[i] + "_date", "#dialog-content-11 #checkNum_" + idArr[i] + "_count").text("");
              }
            }
          } else {
            let newPurchaseRecords = data[key].filter((item, index) => {
              return index < 4;
            })
            for (let j in newPurchaseRecords) {
              $("#dialog-content-11").find("#checkNum_" + idArr[j] + "_date").text(newPurchaseRecords[j].startDate + " 至 " + newPurchaseRecords[j].endDate);
              $("#dialog-content-11").find("#checkNum_" + idArr[j] + "_count").text("购物确认收货数：" + newPurchaseRecords[j].count);
            }
          }
        } else if (key === "vipInfo") {
          if (data[key] === "10") {
            $(".checkNum_vipImg").attr("src", "https://upload.taotaohuitong.com/201908061150522139.xrfxxxxcfapxxxxxxxxxx-77-20.png")
          } else {
            $(".checkNum_vipImg").attr("src", "https://upload.taotaohuitong.com/201908061151103698.png")
          }
        } else {
          if (!$("#dialog-content-11 #checkNum_" + key)) return false;
          $("#dialog-content-11 #checkNum_" + key).text(data[key]);
          $("#dialog-content-11 #checkNum_searchDate").text(dbgjObj.getCurrentDate());
          
        }
      }
      if (autoCheckWw) {
        let foxClassName = Number(data.fox) > 0 ? "dbgj-font-red" : "";
        let jiangNumClassName = Number(data.jiangNum) > 0 ? "dbgj-font-red" : "";
        let html = `<span>降权:</span><span class="${jiangNumClassName}">${data.jiangNum}</span><span class="dbgj-ml-10 ${foxClassName}">狐狸:</span><span>${data.fox}</span>`
        $('.dbgjSellerBox[data-wangwang="'+ autoCheckWw +'"]').find(".dbgjCheckWwResult").removeClass("dbgj-hide").html(html);
      }
    });
    
    // 人像标签分析请求
    ajaxFetch("POST", dbgjBase + "/categoryList", {
      wangwang: ww
    }, function (res) {
      dbgjObj.loadingClose();
      const {
        data,
        code
      } = res;
      if (code === "1") return false;
      $("#checkNum_list_content").empty();
      for (let i in data) {
        let item = `<tr id="list_item">
          <td class="c_name">${data[i].name}</td>
          <td class="c_path">${data[i].path}</td>
          <!-- <td class="c_price">${data[i].price}</td> -->
          <td class="c_fen">${data[i].fen}</td>
          </tr>`;
        $("#checkNum_list_content").append(item);
      }
    });
  });
  // 查实名（骗子）
  $("#checkNum_searchName").click(function () {
    let _self = $(this);
    let ww = $("#checkNum_input").val();
    dbgjObj.loadingOpen();
    ajaxFetch("POST", dbgjBase + "/checkRealName", {
      wangwang: ww
    }, function (res) {
      const {
        data,
        code
      } = res;
      dbgjObj.loadingClose();
      if (code === "1") return false;
      getCurrentUserInfo();
      _self.text(data);
    });
  });

  function tagWeightSearch(isAutoGetPid) {
    // let pid = null;
    // if (isAutoGetPid) {
    //   pid = dbgjObj.getCurrentPageId();
    //   $("#tagWeightProductId").val(pid);
    // } else {
    //   pid = $("#tagWeightProductId").val();
    // }
    let pid = $("#tagWeightProductId").val();
    let ww = $("#tagWeightWw").val();
    if (ww.length === 0) {
      Message("请先输入旺旺号", 3, 3000);
      return false;
    }
    if (pid.length === 0) {
      Message("请先输入商品id或者淘宝链接", 3, 3000);
      return false;
    }
    // 商品信息请求
    ajaxFetch("POST", dbgjBase + "/product/detail", {
      productId: pid
    }, function (res) {
      const {
        code,
        data
      } = res;
      if (code === "1") return;
      $("#dialog-content-12 .dbgj-goods-info-img").attr("src", data.item.images[0]);
      $("#dialog-content-12 .dbgj-goods-info-title").text(data.item.title);
      $("#dialog-content-12 .dbgj-goods-info-shop").text(data.seller.shopName);
      $("#dialog-content-12 .dbgj-goods-info-price").text(data.price);
      $("#dialog-content-12 .dbgj-goods-info-buyerCount").text(data.sales);
    });
    // 标签权重请求
    ajaxFetch("POST", dbgjBase + "/tag/tagInfoSearch", {
      productId: pid,
      wangwang: ww
    }, function (res) {
      const {
        code,
        data
      } = res;
      if (code === 1) return;
      getCurrentUserInfo();
      for (let key in data) {
        $("#dialog-content-12 #tagWeight_" + key).text(data[key]);
      }
    });
  };
  // 标签权重搜索
  $("#dialog-content-12 .dbgj-search-form .search-btn").click(function () {
    tagWeightSearch();
  });
  // 标签权重自动获取
  $("#dialog-content-12 .dbgj-search-form .auto-btn").click(function () {
    let pid = dbgjObj.getCurrentPageId();
    $("#tagWeightProductId").val(pid);
  });
  // 查微信或者qq
  $("#dialog-content-13 .search-btn").click(function () {
    let account = $("#dialog-content-13 #checkWxOrQq").val();
    if (account.length === 0) {
      Message("请先输入微信或者QQ", 3, 3000);
      return;
    }
    if (!account.match(/^[-_A-Za-z0-9]+$/)) {
      Message("不能带有中文", 3, 3000);
      return;
    }
    // 查微信或者qq请求
    ajaxFetch("POST", dbgjBase + "/wxorqq/check", {
      wxorqq: account
    }, function (res) {
      const {
        code,
        data
      } = res;
      if (code === "1") return;
      $("#dialog-content-13 #checkWxOrQqFox").text(data.fox);
      $("#dialog-content-13 #checkWxOrQqFoxResult").empty();
      if (data.info) {
        let info = data.info;
        for(let i in info) {
          let html = `<li><span>${info[i]}</span></li>`;
          $("#dialog-content-13 #checkWxOrQqFoxResult").append(html);
        }
      } else {
        let html = `<li><span>暂无吐槽经历</span></li>`
        $("#dialog-content-13 #checkWxOrQqFoxResult").append(html);
      }
    });
  });
  // 淘客订单查询切换
  $("#dialog-content-14 .dbgj-radio-button").click(function () {
    const index = $(this).index()
    $('.taoke-search').eq(index).addClass('taoke-search_show').siblings().removeClass("taoke-search_show");
    $(this).addClass("selected").siblings(".dbgj-radio-button").removeClass("selected");
  });
  // 淘客一键查询
  $("#taoke-one-key .search-btn").click(function () {
    let order = $("#taoke-one-key .input").val();
    if (order.length === 0) {
      Message("请先输入淘客订单", 3, 3000);
      return;
    }
    // 淘客一键查询请求
    ajaxFetch("POST", dbgjBase + "/taoke/flag", {
      orderNo: order
    }, function (res) {
      const {
        code,
        data
      } = res;
      if (data.queryTime) {
        $("#onekey-taoke-queryTime").text(data.queryTime);
      }
      if (code === "1") {
        $("#dialog-content-14").find(".client-again").removeClass("dbgj-hide").siblings(".tk").addClass("dbgj-hide");
        Message("查询失败，请稍等片刻再进行查询", 3, 3000);
        return;
      }
      Message("查询成功");
      getCurrentUserInfo();
      if (data.isTaoke === 0 || data.isTaoke === '0') {
        $("#dialog-content-14").find(".client-fail").removeClass("dbgj-hide").siblings(".tk").addClass("dbgj-hide");
        return;
      } else if (data.isTaoke === null) {
        $("#dialog-content-14").find(".client-again").removeClass("dbgj-hide").siblings(".tk").addClass("dbgj-hide");
        Message("查询失败，请稍等片刻再进行查询", 3, 3000);
        return;
      } else if (data.isTaoke === 1 || data.isTaoke === '1') {
        $("#dialog-content-14").find(".client-success").removeClass("dbgj-hide").siblings(".tk").addClass("dbgj-hide");
        return;
      }
    })
  });
  // 淘客扫码查询
  $("#taoke-scan .search-btn").click(function () {
    let order = $("#taoke-scan .input").val();
    if (order.length === 0) {
      Message("请先输入淘客订单", 3, 3000);
      return;
    }
    // 淘客扫码查询请求
    ajaxFetch("POST", dbgjBase + "/qr", {
      orderNo: order
    }, function (res) {
      const {
        code,
        data,
        msg
      } = res;
      // $("#onekey-taoke-queryTime").text(data.queryTime);
      if (code === "1") {
        Message(msg, 3, 3000);
        return;
      }
      // 缺少请求时间字段
      $("#scan-search-QrCode").siblings("img").hide();
      $("#scan-search-QrCode").empty();
      $("#scan-search-QrCode").qrcode({
        width: 200,
        height: 200,
        text: data
      });

    })
  });
  //  标签推送搜索
  $("#dialog-content-15 .search-btn").click(function () {
    let keyword = $('#label-push-keyword').val();
    let pid = $("#label-push-productId").val();
    if (keyword.length === 0) {
      Message("请先输入关键词", 3, 3000);
      return;
    }
    if (pid.length === 0) {
      Message("请先输入商品id或淘宝链接", 3, 3000);
      return;
    }
    // 商品信息请求
    ajaxFetch("POST", dbgjBase + "/product/detail", {
      productId: pid
    }, function (res) {
      const {
        code,
        data
      } = res;
      if (code === "1") return;
      $("#dialog-content-15 .dbgj-goods-info-img").attr("src", data.item.images[0]);
      $("#dialog-content-15 .dbgj-goods-info-title").text(data.item.title);
      $("#dialog-content-15 .dbgj-goods-info-shop").text(data.seller.shopName);
      $("#dialog-content-15 .dbgj-goods-info-price").text(data.price);
      $("#dialog-content-15 .dbgj-goods-info-buyerCount").text(data.sales);
    });
  });
  //  标签推送自动获取id 
  $("#dialog-content-15 .auto-btn").click(function () {
    let pid = dbgjObj.getCurrentPageId();
    $("#label-push-productId").val(pid);
    // 商品信息请求
    ajaxFetch("POST", dbgjBase + "/product/detail", {
      productId: pid
    }, function (res) {
      const {
        code,
        data
      } = res;
      if (code === "1") return;
      $("#dialog-content-15 .dbgj-goods-info-img").attr("src", data.item.images[0]);
      $("#dialog-content-15 .dbgj-goods-info-title").text(data.item.title);
      $("#dialog-content-15 .dbgj-goods-info-shop").text(data.seller.shopName);
      $("#dialog-content-15 .dbgj-goods-info-price").text(data.price);
      $("#dialog-content-15 .dbgj-goods-info-buyerCount").text(data.sales);
    });
  });
  // 失去焦点
  $("#label-push-productId").on("blur", function () {
    let pid = $("#label-push-productId").val();
   if ($.isEmpty(pid)) return;
    // 商品信息请求
    ajaxFetch("POST", dbgjBase + "/product/detail", {
      productId: pid
    }, function (res) {
      const {
        code,
        data
      } = res;
      if (code === "1") return;
      $("#dialog-content-15 .dbgj-goods-info-img").attr("src", data.item.images[0]);
      $("#dialog-content-15 .dbgj-goods-info-title").text(data.item.title);
      $("#dialog-content-15 .dbgj-goods-info-shop").text(data.seller.shopName);
      $("#dialog-content-15 .dbgj-goods-info-price").text(data.price);
      $("#dialog-content-15 .dbgj-goods-info-buyerCount").text(data.sales);
    });
  });
  // 标签推送textarea旺旺的个数
  $('#txt_wangwang').bind('input propertychange', function () {
    //进行相关操作 
    let txt = $('#txt_wangwang').val()
    let lines = txt.split(/[(\r\n)\r\n]+/);
    let linesCount = lines.length - (navigator.userAgent.indexOf('MSIE') !== -1);
    $('#iuput_len').text(linesCount);
  });
  // 标签推送请求
  let weightPushRecord = [];

  function weightPushLog(page) {
    let pageCount = parseInt(
      Math.ceil(weightPushRecord.length / 5)
    );
    let fiterWeightPushRecord = weightPushRecord.filter((item, index) => {
      const newIndex = index + 1
      const max = page * 5 //末端数据
      const min = max - 5 + 1 //首端数据
      if (newIndex >= min && newIndex <= max) {
        return item
      }
    })
    $("#label-push-tbody").empty();
    for(let i = 0; i < fiterWeightPushRecord.length; i++) {
      let item = fiterWeightPushRecord[i];
      let statusText = fiterWeightPushRecord[i].status == 0 ? "失败" : "成功"
      let color = fiterWeightPushRecord[i].status == 0 ? "dbgj-font-red" : ""
      let trhtml = `
          <tr class="">
              <td class="dbgj-t-center">${item.productId}</td>
              <td class="dbgj-t-center">${item.wangwang}</td>
              <td class="dbgj-t-center">${item.keyword}</td>
              <td class="dbgj-t-center">手淘搜索</td>
              <td class="dbgj-t-center ${color}">${statusText}</td>
            <!--  <td class="dbgj-t-center">消耗金币</td> -->
              <td class="dbgj-t-center">${item.createTime}</td>
            </tr>`
      $("#label-push-tbody").append(trhtml)
    }
    Page({
      num: pageCount, //页码数
      startnum: page, //指定页码
      elem: $('#wwTagPush-page'), //指定的元素
      callback: function (num) { //回调函数					
        weightPushLog(num);
      }
    });
  }
  // 标签推送
  $('#weightPushBtn').click(function () {
    //文本框参数
    let txt = $('#txt_wangwang').val();
    let keyword = $('#label-push-keyword').val();
    let pid = $("#label-push-productId").val();
    let newTxt = txt.split(/[(\r\n)\r\n]+/)
    let setNewTxt = Array.from(new Set(newTxt));
    let ptitle = $("#dialog-content-15").find(".dbgj-goods-info-title").text();
    if ($.isEmpty(keyword)) {
      MessageBox('标签推送', '关键词不可为空!')
      return
    }
    if ($.isEmpty(pid)) {
      MessageBox('标签推送', '商品id不可为空!')
      return
    }
    if ($.isEmpty(setNewTxt)) {
      MessageBox('标签推送', '旺旺号不可为空!')
      return
    }
    if (newTxt.length > 10) {
      MessageBox('标签推送', '不可大于10个账号!')
      return
    }
    if ($.isEmpty(ptitle)) {
      Message("请先输入商品id获取商品标题");
      return;
    }
    // /wangTag/push
    // /tagpush/record
    //标签推送
    let length = setNewTxt.length
    let num = 1
    //成功状态
    let successStatus = true
    //关键词或者错误状态
    let failStatus = true
    //次数状态
    let buyStatus = true
    //延迟在调用
    setTimeout(() => {
        function getWordCount(num) {
            //标题参数
            const title = $("#dialog-content-15").find(".dbgj-goods-info-title").text()
            //去除空格
            let someCheckNum = $.trim(setNewTxt[num - 1])
            if ($.isEmpty(someCheckNum)) {
                return
            }
            //接口参数
            const opt = {
                productId: pid,
                wangWang: someCheckNum,
                keyword: keyword,
                title: title
            }
            dbgjObj.loadingOpen();
            ajaxFetch("POST", dbgjBase+"/wangTag/push", opt, function(res) {
              getCurrentUserInfo();
              dbgjObj.loadingClose();
              if (res.code == '0') {
                  successStatus = false
              } else if (res.code == '1') {
                  failStatus = false
              } else if (res.code == '-1') {
                  buyStatus = false
              }
            });
          }
     

        let timer = setInterval(() => {
            if (failStatus && buyStatus) {
                getWordCount(num)
                num++
            }
            if (successStatus == false && num > length) {
                num = 0
                setTimeout(() => {
                    ajaxFetch("POST", dbgjBase + '/tagpush/record', {}, function(res) {
                      if (res.code == 0) {
                        weightPushRecord = res.data;
                        weightPushRecord.reverse();
                        weightPushLog(1);
                      } else {
                        Message(res.msg, 3, 3000);
                      }
                    });
                }, 3000)
                clearInterval(timer)
                layer.alert("旺旺标签推送完毕！")
                return
            } else if (failStatus == false) {
                layer.alert('此关键词在商品标题中未搜寻到！')
                clearInterval(timer)
                return
            } else if (buyStatus == false) {
                layer.alert('您的体验次数已用完，请您充值金币后使用！')
                clearInterval(timer)
                return
            }
        }, 1000)
    }, 500)
  });

  // 商家后台自动查黑号
  if (autoCheckWw) {
    $("#dialog-content-11 .dbgj-search-form .search-btn").click();
  }
}
// 数据分析工具
function dataAnalysisToolInit(autoGetIndex) {
  // 基于准备好的dom，初始化echarts实例
  let myChart = echarts.init(document.getElementById('dbgj-goods-analysis-echart'));
  let dataList = [{
    "productId ": "528064755439 ",
    "dateStr ": "2019-05-18 ",
    "payRateIndex ": "22.09% ",
    "uvIndex ": "8244 ",
    "tradeIndex ": "55503 ",
    "payByrCntIndex ": "1822 ",
    "keda ": "30.46 ",
    "uvjz ": "6.73 ",
    "uv ": "21822 ",
    "trade ": "32804 ",
    "payByr ": "35880 ",
    "payRate ": "12032 "
  }, {
    "productId ": "528064755439 ",
    "dateStr ": "2019-05-19 ",
    "payRateIndex ": "23.13% ",
    "uvIndex ": "8242 ",
    "tradeIndex ": "57002 ",
    "payByrCntIndex ": "1907 ",
    "keda ": "29.89 ",
    "uvjz ": "6.92 ",
    "uv ": "21820 ",
    "trade ": "33308 ",
    "payByr ": "36872 ",
    "payRate ": "12344 "
  }, {
    "productId ": "528064755439 ",
    "dateStr ": "2019-05-20 ",
    "payRateIndex ": "22.17% ",
    "uvIndex ": "7292 ",
    "tradeIndex ": "50153 ",
    "payByrCntIndex ": "1616 ",
    "keda ": "31.04 ",
    "uvjz ": "6.88 ",
    "uv ": "20314 ",
    "trade ": "30956 ",
    "payByr ": "33408 ",
    "payRate ": "12056 "
  }, {
    "productId ": "528064755439 ",
    "dateStr ": "2019-05-21 ",
    "payRateIndex ": "20.92% ",
    "uvIndex ": "7621 ",
    "tradeIndex ": "49377 ",
    "payByrCntIndex ": "1594 ",
    "keda ": "30.98 ",
    "uvjz ": "6.48 ",
    "uv ": "20844 ",
    "trade ": "30681 ",
    "payByr ": "33136 ",
    "payRate ": "11672 "
  }, {
    "productId ": "528064755439 ",
    "dateStr ": "2019-05-22 ",
    "payRateIndex ": "20.51% ",
    "uvIndex ": "11912 ",
    "tradeIndex ": "69555 ",
    "payByrCntIndex ": "2444 ",
    "keda ": "28.46 ",
    "uvjz ": "5.84 ",
    "uv ": "27036 ",
    "trade ": "37318 ",
    "payByr ": "42720 ",
    "payRate ": "11544 "
  }, {
    "productId ": "528064755439 ",
    "dateStr ": "2019-05-23 ",
    "payRateIndex ": "19.49% ",
    "uvIndex ": "23739 ",
    "tradeIndex ": "114234 ",
    "payByrCntIndex ": "4630 ",
    "keda ": "24.67 ",
    "uvjz ": "4.81 ",
    "uv ": "40290 ",
    "trade ": "49501 ",
    "payByr ": "62272 ",
    "payRate ": "11224 "
  }, {
    "productId ": "528064755439 ",
    "dateStr ": "2019-05-24 ",
    "payRateIndex ": "20.89% ",
    "uvIndex ": "14596 ",
    "tradeIndex ": "82808 ",
    "payByrCntIndex ": "3048 ",
    "keda ": "27.17 ",
    "uvjz ": "5.67 ",
    "uv ": "30418 ",
    "trade ": "41220 ",
    "payByr ": "48680 ",
    "payRate ": "11664 "
  }];
  // 指定图表的配置项和数据
  let option = {
    tooltip: {
      trigger: 'axis',
      formatter: function (param, ticket, callback) {

        let oneData = dataList[param[0].dataIndex];
        let html = '';
        for (let i = 0; i < param.length; i++) {
          if (i == 0) {
            html += param[i].marker + param[i].seriesName + ':' + oneData.uvIndex + '<br />';
          }
          if (i == 1) {
            html += param[i].marker + param[i].seriesName + ':' + oneData.payByrCntIndex + '<br />';
          }
          if (i == 2) {
            html += param[i].marker + param[i].seriesName + ':' + oneData.tradeIndex + '<br />';
          }
          if (i == 3) {
            html += param[i].marker + param[i].seriesName + ':' + oneData.payRateIndex + '<br />';
          }
        }
        return html;
      }
    },
    tooltip: {
      trigger: 'axis'
    },

    legend: {
      data: ['访客数', '支付买家数', '交易金额', '支付转化率'],
      selected: {
        "支付买家数": false,
        "交易金额": false,
        "支付转化率": false

      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ["08-06 ", "08-07 ", "08-08 ", "08-09 ", "08-10 ", "08-11 ", "08-12 "]
    },
    yAxis: [{
      axisLabel: {
        show: false //这行代码控制着坐标轴x轴的文字是否显示
      },
      splitLine: {
        show: true, // 网格线是否显示
      }
    }],
    series: [{
        name: '访客数',
        type: 'line',
        smooth: true,
        stack: '总量',

        data: uv = ["4180 ", "3646 ", "4341 ", "4128 ", "4371 ", "4969 ", "5565 "],
        color: '#E13B28'


      },
      {
        name: '支付买家数',
        type: 'line',
        smooth: true,
        stack: '总量',
        data: ["688 ", "631 ", "783 ", "748 ", "886 ", "898 ", "1180 "],
        color: '#6DD400'
      },
      {
        name: '交易金额',
        type: 'line',
        smooth: true,
        stack: '总量',
        data: ["24557 ", "22876 ", "28101 ", "26047 ", "31289 ", "31038 ", "37457 "],
        color: '#F7B500'
      },
      {
        name: '支付转化率',
        type: 'line',
        smooth: true,
        stack: '总量',
        data: ["16.46 ", "17.31 ", "18.04 ", "18.12 ", "20.27 ", "18.07 ", "21.2 "],
        color: '#0091FF'
      }
    ]
  };
  // 使用刚指定的配置项和数据显示图表。
  myChart.setOption(option);

  let list_content_product = $("#data_analysis_list_content");
  let list_item_product = $("#data_analysis_list_item");

  let seven_content = $('#data_analysis_seven_content');
  let seven_item = $('#data_analysis_seven_item');
  // 渲染竞品分析的表格数据
  function findProductPage(params) {
    dbgjObj.loadingOpen();
    list_item_product.remove();
    seven_item.remove();
    ajaxFetch("POST", dbgjBase + '/remoteGainAnalysis/product', params, function (res) {
      dbgjObj.loadingClose();
      if (res.code === "1") return;  
      if (res.code === '0') {
        getCurrentUserInfo();
        let data = res.data;
        list_content_product.empty();
        seven_content.empty();
        let payRate = [];
        let trade = [];
        let payByr = [];
        let uv = [];
        let xDate = [];
        //						折线图时间从小到大
        for (let j = data.length - 1; j >= 0; j--) {
          let oneData = data[j];
          let index = data.length - j - 1;
          uv[index] = replace(oneData.uvIndex);
          payRate[index] = replace(oneData.payRateIndex);
          trade[index] = replace(oneData.tradeIndex);
          payByr[index] = replace(oneData.payByrCntIndex);
          dataList[index] = oneData;
          xDate[index] = oneData.dateStr;
        }
        //						表格时间从大到小
        for (let i = 0; i < data.length; i++) {
          // for(var i = data.length - 1; i >= 0; i--) {
          let oneData = data[i];
          let index = i;
          // var index = data.length - i - 1;
          // uv[index] = replace(oneData.uvIndex);
          // payRate[index] = replace(oneData.payRateIndex);
          // trade[index] = replace(oneData.tradeIndex);
          // payByr[index] = replace(oneData.payByrCntIndex);
          // dataList[index] = oneData;
          // xDate[index] = oneData.dateStr;
          let listItem = list_item_product.clone();
          listItem.css('display', '');
          listItem.attr('id', '');
          listItem.find('.sortNo').text(index + 1);
          listItem.find('.dateStr').text(oneData.dateStr);
          listItem.find('.payRateIndex').text(oneData.payRateIndex + "% ");
          listItem.find('.uvIndex').text(oneData.uvIndex);
          listItem.find('.tradeIndex').css('display', '');
          listItem.find('.tradeIndex').text(oneData.tradeIndex);
          listItem.find('.payByrCntIndex').text(oneData.payByrCntIndex);
          listItem.find('.keda').text(oneData.keda);
          listItem.find('.uvjz').text(oneData.uvjz);
          list_content_product.append(listItem);
        };
        if (params.dateType == 1 || params.dateType == 4) {
          $("#dialog-content-21").find('.seven_table').hide();
        } else {
          $("#dialog-content-21").find('.seven_table').show();
        }
        //表格汇总
        $('.senven_len').text(data.length);
        let sum_uvIndex = 0; //7天总买家 
        let sum_payByrCntIndex = 0; //7天总买家 
        let sum_tradeIndex = 0; // 7天总金额
        let sum_payRateIndex = 0; // 7天平均转化率
        let sum_keda = 0; //7天平均客单价
        let sum_uvjz = 0; // 7天平均UV价值
        data.forEach((item, index) => {
          sum_uvIndex = sum_uvIndex + parseFloat(item.uvIndex.replace(/,/g, ""));
          sum_payByrCntIndex = sum_payByrCntIndex + parseFloat(item.payByrCntIndex.replace(/,/g, ""));
          sum_tradeIndex = sum_tradeIndex + parseFloat(item.tradeIndex.replace(/,/g, ""));
          sum_payRateIndex = sum_payRateIndex + parseFloat(item.payRateIndex.replace(/,/g, ""));
          sum_keda = sum_keda + parseFloat(item.keda.replace(/,/g, ""));
          sum_uvjz = sum_uvjz + parseFloat(item.uvjz.replace(/,/g, ""));

        });
        let sumItem = seven_item.clone();
        sumItem.find('.sum_uvIndex').text(sum_uvIndex);
        sumItem.find('.sum_payByrCntIndex').text(sum_payByrCntIndex);
        sumItem.find('.sum_tradeIndex').text(sum_tradeIndex);
        sumItem.find('.sum_payRateIndex').text(parseFloat(sum_payRateIndex / data.length).toFixed(2) + '%');
        sumItem.find('.sum_keda').text(parseFloat(sum_keda / data.length).toFixed(2));
        sumItem.find('.sum_uvjz').text(parseFloat(sum_uvjz / data.length).toFixed(2));
        sumItem.find('.senven_date').text(data[data.length - 1].dateStr + '至' + data[0].dateStr + '(' + data.length + '天)');
        seven_content.append(sumItem);
        myChart.setOption({
          xAxis: {
            data: xDate
          },
          series: [{
              data: uv
            },
            {
              data: payByr
            },
            {
              data: trade
            },
            {
              data: payRate
            }
          ]
        });
      } else {
        list_content_product.empty();
        let payRate = [];
        let trade = [];
        let payByr = [];
        let uv = [];
        let xDate = [];
        myChart.setOption({
          xAxis: {
            data: xDate
          },
          series: [{
              data: uv
            },
            {
              data: payByr
            },
            {
              data: trade
            },
            {
              data: payRate
            }
          ]
        });
        MessageBox("竞品分析", res.msg);
      }
    });
  }
  // 初始化日期选择器
  $('#product-analysis-laydate').datepicker({
    'format': 'yyyy-mm-dd',
    'autoclose': true
  }).on("changeDate", function (e) {
    let pid = $("#productAnalysisId").val();
    let selectDate = $("#product-analysis-laydate").val();
    if ($.isEmpty(pid)) {
      Message("请先输入商品id或者淘宝链接再选择日期查询", 3, 3000);
      return false;
    }
    findProductPage({
      productId: pid,
      dateType: 4,
      dateRange: selectDate
    });
  });
  // 切换天数数据类型
  $("#dialog-content-21 .dbgj-date-pick-box .tab-item").click(function () {
    let pid = $("#productAnalysisId").val();
    if ($.isEmpty(pid)) {
      Message("请先输入商品id或者淘宝链接", 3, 3000);
      return;
    }
    if (!$(this).hasClass("selected")) {
      $(this).addClass("selected").siblings(".tab-item").removeClass("selected");
      let dateType = $(this).attr("data-id");
      findProductPage({
        productId: pid,
        dateType: dateType
      });
    }
  });
  // 竞品分析自动获取
  $("#dialog-content-21 .one-auto-btn").click(function () {
    let pid = dbgjObj.getCurrentPageId();
    $("#productAnalysisId").val(pid);
  });
  // 竞品分析搜索
  $("#dialog-content-21 .search-btn").click(function () {
    let pid = $("#productAnalysisId").val();
    let dateType = $("#dialog-content-21 .dbgj-date-pick-box").find(".tab-item.selected").attr("data-id");
    if ($.isEmpty(pid)) {
      Message("请先输入商品id或者淘宝链接", 3, 3000);
      return;
    }
    // 商品信息请求
    ajaxFetch("POST", dbgjBase + "/product/detail", {
      productId: pid
    }, function (res) {
      const {
        code,
        data
      } = res;
      if (code === "1") return;
      $("#dialog-content-21 .dbgj-goods-info-img").attr("src", data.item.images[0]);
      $("#dialog-content-21 .dbgj-goods-info-title").text(data.item.title);
      $("#dialog-content-21 .dbgj-goods-info-shop").text(data.seller.shopName);
      $("#dialog-content-21 .dbgj-goods-info-price").text(data.price);
      $("#dialog-content-21 .dbgj-goods-info-buyerCount").text(data.sales);
    });
    findProductPage({
      productId: pid,
      dateType: dateType
    });
  });
  // 竞品分析导出数据
  $("#derive-analysis-excel").click(function () {
    let pid = $("#productAnalysisId").val();
    let dateType = $("#dialog-content-21 .dbgj-date-pick-box").find(".tab-item.selected").attr("data-id");
    let selectDate = $("#product-analysis-laydate").val();
    if ($.isEmpty(selectDate)) {
      selectDate = "";
    } else {
      dateType = 4
    }
    if ($.isEmpty(pid)) {
      Message("请先输入商品id或者淘宝链接", 3, 3000);
      return false;
    }
    let params = {
      productId: pid,
      dateType: dateType,
      dateRange: selectDate
    }
    downloadFile("/analysis/product/getAnalysisExportExcel", params, "竞品分析数据-");
  });
  // 关键词查询
  let keywordData = [];
  let impressionIndex = true,
    clickIndex = true,
    ctr = true,
    cvr = true,
    competition = true,
    avgPrice = true,
    lanHai = true;
  // 关键词类目
  function getRelatedWordList(keyword, cateId) {
    // 关键词数据请求
    dbgjObj.loadingOpen();
    ajaxFetch("POST", dbgjBase + "/keyword/relatedWordList", {
      keyword: keyword,
      cateId: cateId
    }, function (res) {
      dbgjObj.loadingClose();
      if (res.code === "1") return;
      getCurrentUserInfo();
      keywordData = res.data.reverse();
      $(".keyword-list-table .sortImg").attr("src", "https://upload.taotaohuitong.com/201910151422032256.png");
      impressionIndex = true;
      clickIndex = true;
      ctr = true;
      cvr = true;
      competition = true;
      avgPrice = true;
      lanHai = true;
      renderKeywordTable(keywordData);
    });
  }
  // 渲染关键词表格
  function renderKeywordTable(keywordData) {
    $("#keyword_search_tbody").removeClass("dbgj-hide");
    if (keywordData.length === 0) {
      $("#keyword_search_tbody").empty();
      let trHtml = `<tr>
        <td>暂无数据</td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
      </tr>`
      $("#keyword_search_tbody").append(trHtml);
    } else {
      $("#keyword_search_tbody").empty()
      for (let i = 0; i < keywordData.length; i++) {
        let item = keywordData[i];
        let trHtml = `<tr>
        <td>${item.word}</td>
        <td>${item.impressionIndex}</td>
        <td>${item.clickIndex}</td>
        <td>${item.ctr}</td>
        <td>${item.cvr}</td>
        <td>${item.competition}</td>
        <td>${item.avgPrice}</td>
        <td>${item.lanHai}</td>
      </tr>`;
        $("#keyword_search_tbody").append(trHtml);
      }
    }
  }

  // 关键词年龄分布echart
  // 年龄饼图
  var ageChart = echarts.init(document.getElementById('chart_age'));
  var age_data = [{
    name: "18-24岁",
    value: 2969,
    age: 18
  }, {
    name: "25-29岁",
    value: 2793,
    age: 25
  }, {
    name: "30-34岁",
    value: 1514,
    age: 30
  }, {
    name: "40-49岁",
    value: 796,
    age: 40
  }, {
    name: "50岁+",
    value: 1183,
    age: 50
  }];
  // 指定图表的配置项和数据
  var option3 = {
    title: {
      text: "年龄主要集中在18-24岁，25-29岁，30-34岁",
      x: 'center',
      y: '5px',
      textStyle: {
        color: "#ea3323",
        fontSize: 13,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: "{a} <br/>{b} : {c} ({d}%)"
    },
    series: [{
      name: '年龄范围',
      type: 'pie',
      color: ['#f11d0a', '#ec394a', '#e6665a', '#e49992', '#e0afab'],
      fontSize: '13px',
      radius: ['40%', '55%'],
      data: age_data,
      itemStyle: {
        emphasis: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  };
  if (option3 && typeof option3 === "object") {
    ageChart.setOption(option3, true);
  }

  // 类目单价
  var fenlei = echarts.init(document.getElementById('zodiac-echart'));
  var fenlei_data = [70, 60, 50, 40, 20]
  var fenlei_titlename = ['类目笔单价0-20', '类目笔单价20-50', '类目笔单价50-100', '类目笔单价100-300', '类目笔单价300以上'];
  // var valdata = [550, 400, 300, 200, 100];
  var valdata = [];

  var myColor = ['#ea3323'];
  option = {
    backgroundColor: '#fff',
    title: {
      text: "类目笔单价主要集中在20-50、0-20、50-100",
      x: 'center',
      y: '15px',
      textStyle: {
        color: "#ea3323",
        fontSize: 13,
        fontWeight: 'bold'
      }
    },

    xAxis: {
      show: false
    },
    grid: {
      width:'400px',
      left: '4%',
      right: '4%',
      containLabel: true
    },
    yAxis: [{
      show: true,
      data: fenlei_titlename,
      inverse: true,
      axisLine: {
        show: false
      },
      splitLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        color: '#000',
        formatter: function(value, index) {
          return [
            '{lg|' + (index + 1) + '}' + '{title|' + value + '} '
          ].join('\n')
        },
        rich: {
          lg: { //y轴的汉字
            backgroundColor: '#fff',
            color: '#fff',
            borderRadius: 10,
            padding: 5,
            align: 'left',
            width: 10,
            height: 7
          },
        }
      },


    }, {
      show: true,
      inverse: true,
      data: valdata,
      axisLabel: {
        textStyle: {
          fontSize: 13,
          color: '#000',
        },
      },
      axisLine: {
        show: false
      },
      splitLine: {
        show: false
      },
      axisTick: {
        show: false
      },

    }],
    series: [{
      name: '条', //显示数据条
      type: 'bar',
      yAxisIndex: 0,
      data: fenlei_data,
      barWidth: 15,
      itemStyle: {
        normal: {
          barBorderRadius: 30,
          color: function(params) {
            var num = myColor.length;
            return myColor[params.dataIndex % num]
          },
        }
      },
      label: {
        normal: {
          show: true,
          position: 'right',
          formatter: '{c}%'
        }
      },
    }, {
      name: '框', //外框
      type: 'bar',
      yAxisIndex: 1,
      barGap: '-100%',
      data: [100, 100, 100, 100, 100],
      barWidth: 15,
      itemStyle: {
        normal: {
          color: 'none',
          borderColor: '#ea3323',
          borderWidth: 1,
          barBorderRadius: 15,
        }
      }
    }, ]
  };
  fenlei.setOption(option);
  window.onresize = fenlei.resize;
  // 消费层级
  var free_data = [70, 60, 50, 40, 20, 15, 10]
  var free_titlename = ['消费层级1750', '消费层级1050-1750', '消费层级750-1050', '消费层级550-750', '消费层级400-500', '消费层级300-400',
    '消费层级0-300'
  ];
  // var free_valdata = [1750, 1350, 1000, 550, 450,350,250];
  var free_valdata = [];
  var freeChart = echarts.init(document.getElementById('free-echart'));
  option1 = {
    backgroundColor: '#fff',
    title: {
      text: "消费层级主要集中在1750以上、0-300、1050-1750",
      x: 'center',
      y: '15px',
      textStyle: {
        color: "#ea3323",
        fontSize: 13,
        fontWeight: 'bold'
      }
    },

    xAxis: {
      show: false
    },
    grid: {
      width:'400px',
      left: '4%',
      right: '4%',
      containLabel: true
    },
    yAxis: [{
      show: true,
      data: free_titlename,
      inverse: true,
      axisLine: {
        show: false
      },
      splitLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        color: '#000',
        formatter: function(value, index) {
          return [
            '{lg|' + (index + 1) + '}' + '{title|' + value + '} '
          ].join('\n')
        },
        rich: {
          lg: { //y轴的汉字
            backgroundColor: '#fff',
            color: '#fff',
            borderRadius: 10,
            padding: 5,
            align: 'left',
            width: 10,
            height: 7
          },
        }
      },


    }, {
      show: true,
      inverse: true,
      data: free_valdata,
      axisLabel: {
        textStyle: {
          fontSize: 13,
          color: '#000',
        },
      },
      axisLine: {
        show: false
      },
      splitLine: {
        show: false
      },
      axisTick: {
        show: false
      },

    }],
    series: [{
      name: '条', //显示数据条
      type: 'bar',
      yAxisIndex: 0,
      data: free_data,
      barWidth: 15,
      itemStyle: {
        normal: {
          barBorderRadius: 30,
          color: function(params) {
            var num = myColor.length;
            return myColor[params.dataIndex % num]
          },
        }
      },
      label: {
        normal: {
          show: true,
          position: 'right',
          formatter: '{c}%'
        }
      },
    }, {
      name: '框', //外框
      type: 'bar',
      yAxisIndex: 1,
      barGap: '-100%',
      data: [100, 100, 100, 100, 100, 100, 100],
      barWidth: 15,
      itemStyle: {
        normal: {
          color: 'none',
          borderColor: '#ea3323',
          borderWidth: 1,
          barBorderRadius: 15,
        }
      }
    }, ]
  };
  freeChart.setOption(option1);
  window.onresize = freeChart.resize;

  function compare(property){
    return function(a,b){
        var value1 = a[property];
        var value2 = b[property];
        return value1 - value2;
    }
  }
  // 年龄性别消费分布
  function keywordFeatures(keyword, cateId) {
    ajaxFetch("POST", dbgjBase + "/keyword/features", {keyword:keyword, cateId: cateId}, function(res) {
      const { code, data:resData, msg } = res;
      if (code == 0) {
        // 性别分布
        let sexRatio_data = resData.gender;
        $("#features_gender").find(".userCntExplain").text(sexRatio_data.userCntExplain);
        $("#features_gender").find(".cvrExplain").text(sexRatio_data.cvrExplain);
        let progress_data = sexRatio_data.data;
        for (let i = 0; i < progress_data.length; i++) {
          if (progress_data[i].genderName === "女") {
            $("#features_gender").find(".female_userCntWordRate").text(progress_data[i].userCntWordRate);
            $("#features_gender").find(".female_userCntCateRate").text(progress_data[i].userCntCateRate);
          } 
          if (progress_data[i].genderName === "男") {
            $("#features_gender").find(".male_userCntWordRate").text(progress_data[i].userCntWordRate);
            $("#features_gender").find(".male_userCntCateRate").text(progress_data[i].userCntCateRate);
          } 
        }
        // 年龄分布
        age_data = resData.age.data;
        // 年龄分布
        // $('.age_userCntExplain').text(resdata_one.age.userCntExplain);
        // age_data = resdata_one.age.data;
        let age_userCntWordIndex_sum=0;
        age_data.forEach((item, index) => {				
          age_userCntWordIndex_sum=parseFloat(item.userCntWordIndex)+age_userCntWordIndex_sum;	
          
          age_data[index].name = '18-24岁';
          if (item.tagValueName == '95后') {
            age_data[index].name = '18-24岁';
          } else if (item.tagValueName == '90后') {
            age_data[index].name = '25-29岁';
          } else if (item.tagValueName == '85后') {
            age_data[index].name = '30-34岁';
          } else if (item.tagValueName == '80后') {
            age_data[index].name = '35-40岁';
          } else if (item.tagValueName == '70后') {
            age_data[index].name = '40-49岁';
          } else {
            age_data[index].name = '50+岁';
          }
        });
        setTimeout(function(){
          age_data.forEach((item, index) => {
            age_data[index].value=parseFloat(parseFloat(item.userCntWordIndex)/age_userCntWordIndex_sum).toFixed(2);				
          });
          ageChart = echarts.init(document.getElementById('chart_age'));
          ageChart.setOption({
            title: {
              text: resData.age.userCntExplain,
            },
            series: [{
              data: age_data
            }]
          });
         ageChart.resize();
        },100)
        // 消费层级
        let consumerLevel_data = resData.consumerLevel.data;
        consumerLevel_data=consumerLevel_data.sort(compare('userCntWordIndex')).reverse()
        free_data = [];
        free_titlename = [];
        free_valdata = [];
        let userCntWordIndex_sum=0;
        consumerLevel_data.forEach((item, index) => {				
          userCntWordIndex_sum=parseFloat(item.userCntWordIndex)+userCntWordIndex_sum;	
        });
        setTimeout(function(){
          consumerLevel_data.forEach((item, index) => {
            // free_data.push(parseFloat(parseFloat(item.userCntWordIndex)/userCntWordIndex_sum).toFixed(2));
            let a=parseFloat(parseFloat(item.userCntWordIndex)/userCntWordIndex_sum).toFixed(2);
            a=parseInt(a*100);
            free_data.push(a)
    
            free_titlename.push(item.tagName + item.tagValueName);
            free_valdata.push(item.userCntWordIndex);
          });
          freeChart = echarts.init(document.getElementById('free-echart'));
          freeChart.setOption({
            title: {
              text: resData.consumerLevel.userCntExplain,
            },
            yAxis: [{
              show: true,
              data: free_titlename
            }],
            series: [{
              data: free_data,
              label: {
                normal: {
                  show: true,
                  position: 'right',
                  formatter: '{c}%',
                  
                }
              },
              
            }]
          });
          freeChart.resize();
        },100)
        // 类目比单价
        let unitCost_data = resData.unitCost.data;
        unitCost_data=unitCost_data.sort(compare('userCntWordIndex')).reverse()
        fenlei_data = [];
        fenlei_titlename = [];
        valdata = [];
        let unitCost_userCntWordIndex_sum=0;
        unitCost_data.forEach((item, index) => {				
          unitCost_userCntWordIndex_sum=parseFloat(item.userCntWordIndex)+unitCost_userCntWordIndex_sum;	
        });
        setTimeout(function(){
          unitCost_data.forEach((item, index) => {
            // fenlei_data.push(parseFloat(parseFloat(item.userCntWordIndex)/unitCost_userCntWordIndex_sum).toFixed(2));
            let a=parseFloat(parseFloat(item.userCntWordIndex)/unitCost_userCntWordIndex_sum).toFixed(2);
            a=parseInt(a*100);
            fenlei_data.push(a)
            fenlei_titlename.push(item.tagName + item.tagValueName);
            valdata.push(item.userCntWordIndex);
          });
          fenlei = echarts.init(document.getElementById('zodiac-echart'));
          fenlei.setOption({
            title: {
              text: resData.unitCost.userCntExplain,
            },
            yAxis: [{
              data: fenlei_titlename
            }],
            series: [{
              data: fenlei_data,
              label: {
                normal: {
                  show: true,
                  position: 'right',
                  formatter: '{c}%'
                }
              },
              
            }]
          });
          fenlei.resize();
        },100)
      }
    });
  }
  // 地域分布
  //地域分布接口
  let regionArr = [];
  // 计算百分比
  function GetPercent(small, big) {
    /// 求百分比
    let percentage = (small / big * 100).toFixed(0) + '%'
    return percentage
  };
  function renderRegion(eleId, dataArr) {
    let newArr = dataArr;
    $("#"+ eleId).empty();
        for (let i = 0; i < newArr.length; i++) {
          let index = 1;
          let item = newArr[i];
          if (i < 3) {
            index = `<img src="https://upload.sdjr.online/202003021058088496.png" alt="">`
          } else {
            index += i; 
          }
          let trHtml = `
          <tr>
            <td>${index}</td>
            <td>${item.provinceName}</td>
            <td style="display: flex;align-items: center;justify-content: space-around;width: 200px">
              <span>${item.value}</span>
              <span class="subway-pluskI" style="width: 100px;">
                <div class="subway-pluskJ" style="width: ${item.percentage};  background: #ea3323; ">
                </div>
              </span>
            </td>
          </tr>`;
          $("#"+ eleId).append(trHtml);
        }
  }
  function region(keyword, cateId, type) {
    let parm = {
      keyword: keyword,
      cateId: cateId,
      type: type
    };
    ajaxFetch("POST", dbgjBase + '/keyword/region', parm, function(res) {
      if (res.code == 0) {  
        regionArr = [];
        let data = res.data;
        regionArr.push(data)
        let impressionIndex = data.sort((a, b) => {
          return b.impressionIndex - a.impressionIndex
        })
        let newArr = impressionIndex.map(item => {
          let percentage = GetPercent(item.impressionIndex, impressionIndex[0].impressionIndex)
          return {
            provinceName: item.provinceName,
            value: item.impressionIndex,
            percentage: percentage
          }
        });
        renderRegion("region", newArr);
      } else {
        Message(res.msg, 3, 3000);
      }

    });

  }

  // 关键词搜索
  $("#dialog-content-22").find(".search-btn").click(function () {
    let keyword = $("#keywordInput").val();
    if ($.isEmpty(keyword)) {
      Message("请先输入关键词", 3, 3000);
      return;
    }
    // 关键词类目请求
    dbgjObj.loadingOpen();
    ajaxFetch("POST", dbgjBase + "/keyword/CategoryList", {
      keyword: keyword
    }, function (res) {
      const {
        code,
        data,
        msg
      } = res;
      if (code === "1") {
        return;
      }
      $("#keyword_content").show().empty();
      getRelatedWordList(keyword, data[0].cateId);
      keywordFeatures(keyword, data[0].cateId);
      let type = $("#select_day").children('option:selected').attr('data-type');
      region(keyword, data[0].cateId, type);
      data.reverse();
      for (let i in data) {
        let item = `
        <span class="cate-item" data-cateid="${data[i].cateId}">											
            <input class="dbgj-radio-type" name="cateName" type="radio" id="${data[i].cateId}" value="${data[i].cateName}">
            <label for="${data[i].cateId}">${data[i].cateName}</label>
          </span>`;
        $("#keyword_content").append(item);
      }
      $('#keyword_content .dbgj-radio-type:first').attr('checked', "checked")
    });

  });
  //单选
  $('#keyword_content').on('change', '.dbgj-radio-type', function () {
    let cateId = $(this).attr("id");
    let keyword = $("#keywordInput").val();
    if ($.isEmpty(keyword)) {
      Message("请先输入关键词", 3, 3000);
      return;
    }
    getRelatedWordList(keyword, cateId);
    keywordFeatures(keyword, cateId);
    let type = $("#select_day").children('option:selected').attr('data-type');
    region(keyword, cateId, type);
  });
  // 导出关键词数据
  $("#derive-keyword-excel").click(function () {
    let cateId = $('#keyword_content').find("input[type='radio']:checked").attr("id");
    let keyword = $("#keywordInput").val();
    if ($.isEmpty(keyword)) {
      Message("请先输入关键词", 3, 3000);
      return;
    }
    downloadFile("/keyword/getExportExcel", {
      cateId: cateId,
      keyword: keyword
    }, "关键词查询数据");
  });
  //排序按钮
  $('.keyword-list-table .sortImg').click(function () {
    const index = $(this).data('id');
    let newData = keywordData;
    switch (index) {
      // case 0:
      //     if (relevance) {
      //         newData.sort(function (a, b) {
      //             return b.relevance - a.relevance
      //         })
      //         const keyWordInfo = template('keyWordInfoTemp', newData)
      //         $('#keyWordInfo').html(keyWordInfo)
      //         relevance = false
      //         $(this).attr('src', 'https://upload.taotaohuitong.com/201910301223217266.png')
      //     } else {
      //         newData.sort(function (a, b) {
      //             return a.relevance - b.relevance
      //         })
      //         const keyWordInfo = template('keyWordInfoTemp', newData)
      //         $('#keyWordInfo').html(keyWordInfo)
      //         relevance = true
      //         $(this).attr('src', 'https://upload.taotaohuitong.com/201910301223198003.png')
      //     }
      //     break;
      case 1:
        if (impressionIndex) {
          newData.sort(function (a, b) {
            return b.impressionIndex - a.impressionIndex
          })
          renderKeywordTable(newData);
          impressionIndex = false
          $(this).attr('src', 'https://upload.taotaohuitong.com/201910151423486115.png')
        } else {
          newData.sort(function (a, b) {
            return a.impressionIndex - b.impressionIndex
          })
          renderKeywordTable(newData);
          impressionIndex = true
          $(this).attr('src', 'https://upload.taotaohuitong.com/201910151423516898.png')
        }
        break;
      case 2:
        if (clickIndex) {
          newData.sort(function (a, b) {
            return b.clickIndex - a.clickIndex
          })
          renderKeywordTable(newData);
          clickIndex = false
          $(this).attr('src', 'https://upload.taotaohuitong.com/201910151423486115.png')
        } else {
          newData.sort(function (a, b) {
            return a.clickIndex - b.clickIndex
          })
          renderKeywordTable(newData);
          clickIndex = true
          $(this).attr('src', 'https://upload.taotaohuitong.com/201910151423516898.png')
        }
        break;
      case 3:
        if (ctr) {
          newData.sort(function (a, b) {
            return b.ctr - a.ctr
          })
          renderKeywordTable(newData);
          ctr = false
          $(this).attr('src', 'https://upload.taotaohuitong.com/201910151423486115.png')
        } else {
          newData.sort(function (a, b) {
            return a.ctr - b.ctr
          })
          renderKeywordTable(newData);
          ctr = true
          $(this).attr('src', 'https://upload.taotaohuitong.com/201910151423486115.png')
        }
        break;
      case 4:
        if (cvr) {
          newData.sort(function (a, b) {
            return b.cvr - a.cvr
          })
          renderKeywordTable(newData);
          cvr = false
          $(this).attr('src', 'https://upload.taotaohuitong.com/201910151423486115.png')
        } else {
          newData.sort(function (a, b) {
            return a.cvr - b.cvr
          })
          renderKeywordTable(newData);
          cvr = true
          $(this).attr('src', 'https://upload.taotaohuitong.com/201910151423486115.png')
        }
        break;
      case 5:
        if (competition) {
          newData.sort(function (a, b) {
            return b.competition - a.competition
          })
          renderKeywordTable(newData);
          competition = false
          $(this).attr('src', 'https://upload.taotaohuitong.com/201910151423486115.png')
        } else {
          newData.sort(function (a, b) {
            return a.competition - b.competition
          })
          renderKeywordTable(newData);
          competition = true
          $(this).attr('src', 'https://upload.taotaohuitong.com/201910151423486115.png')
        }
        break;
      case 6:
        if (avgPrice) {
          newData.sort(function (a, b) {
            return b.avgPrice - a.avgPrice
          })
          renderKeywordTable(newData);
          avgPrice = false
          $(this).attr('src', 'https://upload.taotaohuitong.com/201910151423486115.png')
        } else {
          newData.sort(function (a, b) {
            return a.avgPrice - b.avgPrice
          })
          renderKeywordTable(newData);
          avgPrice = true
          $(this).attr('src', 'https://upload.taotaohuitong.com/201910151423486115.png')
        }
        break;
      case 7:
        if (lanHai) {
          newData.sort(function (a, b) {
            return b.lanHai - a.lanHai
          })
          renderKeywordTable(newData);
          lanHai = false
          $(this).attr('src', 'https://upload.taotaohuitong.com/201910151423486115.png')
        } else {
          newData.sort(function (a, b) {
            return a.lanHai - b.lanHai
          })
          renderKeywordTable(newData);
          lanHai = true
          $(this).attr('src', 'https://upload.taotaohuitong.com/201910151423486115.png')
        }
        break;
    }
  })
  // 切换消费层级和类目比单价
  $("#toggle_consumerLevel .section-select-item").click(function() {
    $(this).addClass("selected").siblings(".section-select-item").removeClass("selected");
    if ($(this).index() == "0") {
      $("#free-echart").closest(".box").show();
      $("#zodiac-echart").closest(".box").hide();
    } else {
      $("#zodiac-echart").closest(".box").show();
      $("#free-echart").closest(".box").hide();
    }
  })
  // 选择地域分布的日期类型
  $("#select_day").change(function() {
		let keyword = $('#keywordInput').val();
		if ($.isEmpty(keyword)) {
			MessageBox("地域分布","关键词不能为空!");
			return;
		}
		let type = $(this).children('option:selected').attr('data-type');
		let cateId = $("#keyword_content").find(".dbgj-radio-type:checked").attr('id');
		region(keyword, cateId, type)
  });
  // 选择地域分布的指数类型
  $("#select_region").change(function() {
		let keyword = $('#keywordInput').val();
		if ($.isEmpty(keyword)) {
			MessageBox("地域分布", "关键词不能为空!");
			return;
		}
		let txt = $(this).children('option:selected').val();
		let id = $(this).children('option:selected').attr('data-select_id');
		switch (id) {
			//展现指数 排序筛选
			case '0':
			
				let sortOne = regionArr[0].sort((a, b) => {
					return b.impressionIndex - a.impressionIndex
				})
				let impressionIndex = sortOne.map(item => {
					let percentage = GetPercent(item.impressionIndex, regionArr[0][0].impressionIndex)
					return {
						value: item.impressionIndex,
						provinceName: item.provinceName,
						percentage: percentage
					}
				})
				renderRegion("region", impressionIndex);
				break;
				//点击指数 排序筛选
			case '1':

				let sortTwo = regionArr[0].sort((a, b) => {
					return b.clickIndex - a.clickIndex
				})
				let clickIndex = sortTwo.map(item => {
					let percentage = GetPercent(item.clickIndex, regionArr[0][0].clickIndex)
					return {
						value: item.clickIndex,
						provinceName: item.provinceName,
						percentage: percentage
					}
				})
				renderRegion("region", clickIndex);
				break;
				//点击率 排序筛选
			case '2':
				let sortThree = regionArr[0].sort((a, b) => {
					return b.ctrIndex - a.ctrIndex
				})
				let ctrIndex = sortThree.map(item => {
					let percentage = GetPercent(item.ctrIndex, regionArr[0][0].ctrIndex)
					return {
						value: item.ctrIndex + '%',
						provinceName: item.provinceName,
						percentage: percentage
					}
				})
				renderRegion("region", ctrIndex);
				break;
				//点击转化率 排序筛选
			case '3':
				let sortFour = regionArr[0].sort((a, b) => {
					return b.cvrIndex - a.cvrIndex
				})
				let cvrIndex = sortFour.map(item => {
					let percentage = GetPercent(item.cvrIndex, regionArr[0][0].cvrIndex)
					return {
						value: item.cvrIndex + '%',
						provinceName: item.provinceName,
						percentage: percentage
					}
				})
				renderRegion("region", cvrIndex);
				break;
				//平均点击均价 排序筛选
			case '4':
				let sortFive = regionArr[0].sort((a, b) => {
					return b.cpcIndex - a.cpcIndex
				})
				let cpcIndex = sortFive.map(item => {
					let percentage = GetPercent(item.cpcIndex, regionArr[0][0].cpcIndex)
					return {
						value: item.cpcIndex + '元',
						provinceName: item.provinceName,
						percentage: percentage
					}
				})
				renderRegion("region", cpcIndex);
				break;
				//竞争度 排序筛选
			case '5':
				let sortSix = regionArr[0].sort((a, b) => {
					return b.competition - a.competition
				})
				let competition = sortSix.map(item => {
					let percentage = GetPercent(item.competition, regionArr[0][0].competition)
					return {
						value: item.competition,
						provinceName: item.provinceName,
						percentage: percentage
					}
				})
				renderRegion("region", competition);
				break;
		}
  });

  // 入店来源自动获取
  $("#dialog-content-23 .one-auto-btn").click(function () {
    let pid = dbgjObj.getCurrentPageId();
    $("#sourceofinletId").val(pid);
  });
  // 入店来源搜索
  $("#dialog-content-23 .search-btn").click(function () {
    let pid = $("#sourceofinletId").val();
    let dateType = $("#dialog-content-23 .dbgj-date-pick-box").find(".tab-item.selected").attr("data-id");
    if ($.isEmpty(pid)) {
      Message("请先输入商品id或者淘宝链接", 3, 3000);
      return;
    }
    // 商品信息请求
    ajaxFetch("POST", dbgjBase + "/product/detail", {
      productId: pid
    }, function (res) {
      const {
        code,
        data
      } = res;
      if (code === "1") return;
      $("#dialog-content-23 .dbgj-goods-info-img").attr("src", data.item.images[0]);
      $("#dialog-content-23 .dbgj-goods-info-title").text(data.item.title);
      $("#dialog-content-23 .dbgj-goods-info-shop").text(data.seller.shopName);
      $("#dialog-content-23 .dbgj-goods-info-price").text(data.price);
      $("#dialog-content-23 .dbgj-goods-info-buyerCount").text(data.sales);
    });
    sourceofinletPage({
      productId: pid,
      type: dateType
    });
    $(".sourceofinlet-list-table .sortImg").attr("src", "https://upload.taotaohuitong.com/201910151423486115.png");
  });
  // 竞品分析日期选择
  // 切换天数数据类型
  $("#dialog-content-23 .dbgj-date-pick-box .tab-item").click(function () {
    let pid = $("#sourceofinletId").val();
    if ($.isEmpty(pid)) {
      Message("请先输入商品id或者淘宝链接", 3, 3000);
      return;
    }
    if (!$(this).hasClass("selected")) {
      $(this).addClass("selected").siblings(".tab-item").removeClass("selected");
      let dateType = $(this).attr("data-id");
      sourceofinletPage({
        productId: pid,
        type: dateType,
      });
      $(".sourceofinlet-list-table .sortImg").attr("src", "https://upload.taotaohuitong.com/201910151423486115.png");
    }
  });
   // 初始化日期选择器
  //  $('#analysis-sourceofinlet-laydate').datepicker({
  //   'format': 'yyyy-mm-dd',
  //   'autoclose': true
  // }).on("changeDate", function (e) {
  //   let selectDate = $("#analysis-sourceofinlet-laydate").val();
  //   let pid = $("#sourceofinletId").val();
  //   if ($.isEmpty(pid)) {
  //     Message("请先输入商品id或者淘宝链接", 3, 3000);
  //     return;
  //   }
  //   // sourceofinletPage({
  //   //   productId: pid,
  //   //   dateRange: selectDate,
  //   //   dateType: "4",
  //   //   sort: "desc"
  //   // });
  //   // $(".sourceofinlet-list-table .sortImg").attr("src", "https://upload.taotaohuitong.com/201910151423486115.png");
  // });
  // 切换排序
  $(".sourceofinlet-list-table .sortImg").click(function() {
    let sortFlag = $(this).attr("data-sort");
    let sort = ""
    if (sortFlag === "desc") {
      $(this).attr("data-sort", "asc");
      sort = "asc";
      $(this).attr("src", "https://upload.taotaohuitong.com/201910151423516898.png");
    } else {
      $(this).attr("data-sort", "desc");
      sort = "desc";
      $(this).attr("src", "https://upload.taotaohuitong.com/201910151423486115.png");
    }
    if (sourceofinletData.length === 0) {
      Message("请先获取到数据再排序", 3, 3000);
      return;
    }

    let data = [];
    $("#sourceofinlet_tbody").empty();
    // 103674
    if (sort === "desc") {
      data = sourceofinletData.sort((a, b) => {
        return b.uvIndex - a.uvIndex
      });
      for(let i in data) {
        let children = data[i].children.sort((a, b) => {
          return b.uvIndex - a.uvIndex
        });
        data[i].children = children;
      }
      
    } else {
      data = sourceofinletData.sort((a, b) => {
        return a.uvIndex - b.uvIndex
      });
      for(let i in data) {
        let children = data[i].children.sort((a, b) => {
          return a.uvIndex - b.uvIndex
        });
        data[i].children = children;
      }
    }
    for (let i = 0; i < data.length; i++) {
      let secondData = data[i].children;
      // secondData.reverse();
      let length = data[i].children.length;
      for (let j=0; j < secondData.length; j++) {
        if (j===0) {
          let itemHtml = `<tr>
            <td class="date" rowspan="${length}">${data[i].date}</td>
            <td class="fristLevel" rowspan="${length}">${data[i].pageName}</td>
            <td class="secondLevel">${secondData[j].pageName}</td>
            <td class="sl_uvIndex">${secondData[j].uvIndex}</td>
            <td class="sl_tradeIndex">${secondData[j].tradeIndex}</td>
            <td class="sl_payRateIndex">${secondData[j].payRateIndex}</td>
            <td class="sl_uvValue">${secondData[j].uvValue}</td>
          </tr>`;
          $("#sourceofinlet_tbody").append(itemHtml);
        } else {
          let itemHtml = `<tr>
            <td class="date" style="display:none">${data[i].date}</td>
            <td class="fristLevel" style="display:none">${data[i].pageName}</td>
            <td class="secondLevel">${secondData[j].pageName}</td>
            <td class="sl_uvIndex">${secondData[j].uvIndex}</td>
            <td class="sl_tradeIndex">${secondData[j].tradeIndex}</td>
            <td class="sl_payRateIndex">${secondData[j].payRateIndex}</td>
            <td class="sl_uvValue">${secondData[j].uvValue}</td>
          </tr>`;
          $("#sourceofinlet_tbody").append(itemHtml);
        }
        
      }
    }
  });
  // 导出入店来源数据
  $("#derive-sourceofinlet-excel").click(function () {
    let pid = $("#sourceofinletId").val();
    // let sort = $(".sourceofinlet-list-table .sortImg").attr("data-sort");
    let dateType = $("#dialog-content-23 .dbgj-date-pick-box").find(".tab-item.selected").attr("data-id");
    // let selectDate = $("#analysis-sourceofinlet-laydate").val();
    let params = {
      productId: pid,
      type: dateType
    }
    downloadFile("/sourceofinlet/getExportExcel", params, "入店来源数据-");
  });
  let sourceofinletData = [], sourceofinletDate = "";
  function sourceofinletPage(params) {
    let date = params.type == "1" ? "昨日" : "7日";
    sourceofinletDate = date;
    $("#sourceofinlet_tbody").empty();
    dbgjObj.loadingOpen();
    ajaxFetch("POST", dbgjBase + "/analysis/sourceofinlet", params, function(res) {
      dbgjObj.loadingClose();
      const { code, data:resData, msg } = res;
      if (code === "1") return;
      if (code === "0") {
        if(resData.length === 0) {
          Message("暂无数据",3, 3000);
          return;
        }
        sourceofinletData = resData;
        for (let i = 0; i < resData.length; i++) {
          let secondData = resData[i].children;
          // secondData.reverse();
          let length = resData[i].children.length;
          for (let j=0; j < secondData.length; j++) {
            if (j===0) {
              let itemHtml = `<tr>
                <td class="date" rowspan="${length}">${resData[i].date}</td>
                <td class="fristLevel" rowspan="${length}">${resData[i].pageName}</td>
                <td class="secondLevel">${secondData[j].pageName}</td>
                <td class="sl_uvIndex">${secondData[j].uvIndex}</td>
                <td class="sl_tradeIndex">${secondData[j].tradeIndex}</td>
                <td class="sl_payRateIndex">${secondData[j].payRateIndex}</td>
                <td class="sl_uvValue">${secondData[j].uvValue}</td>
              </tr>`;
              $("#sourceofinlet_tbody").append(itemHtml);
            } else {
              let itemHtml = `<tr>
                <td class="date" style="display:none">${resData[i].date}</td>
                <td class="fristLevel" style="display:none">${resData[i].pageName}</td>
                <td class="secondLevel">${secondData[j].pageName}</td>
                <td class="sl_uvIndex">${secondData[j].uvIndex}</td>
                <td class="sl_tradeIndex">${secondData[j].tradeIndex}</td>
                <td class="sl_payRateIndex">${secondData[j].payRateIndex}</td>
                <td class="sl_uvValue">${secondData[j].uvValue}</td>
              </tr>`;
              $("#sourceofinlet_tbody").append(itemHtml);
            }
          }
        }
      }
    });
  }
  
  // $("#dialog-content-22 .eachrtTab>span").click(function() {
  //   $(this).addClass("eachrtActive").siblings().removeClass("eachrtActive");
  //   console.log($(this).index());
  // });
  // $("#dialog-content-22 .eachrtDayContentList").click(function() {
  //   let type = $(this).attr("data-type");
  //   let text = $(this).text();
  //   $("#dialog-content-22").find(".eachrtDayName").text(text);
  //   console.log(type);
  // })
  if (autoGetIndex == 21) {
    $("#dialog-content-21 .one-auto-btn").click();
    $("#dialog-content-21 .search-btn").click();
  } 
}
// 详情页工具
function detailsToolInit(autoGetIndex) {
  // sku自动获取
  $("#sku-buyer-show-search .one-auto-btn").click(function () {
    $("#sku-input").val(dbgjObj.getCurrentPageId);
  });
  
  function myChart() {
    // 基于准备好的dom，初始化echarts实例
    var myChart = echarts.init(document.getElementById('skuPieChart'));
    // 指定图表的配置项和数据
    option = {
      tooltip: {
        trigger: 'item',
        formatter: "{a} <br/>{b} : {c} ({d}%)"
      },
      series: [{
        name: '访问来源',
        type: 'pie',
        color: ['#1790FF', '#F98F37', '#FED137', '#8196FE', '#46D694', '#F98F37'],
        radius: ['50%', '70%'],
        data: [{
          value: 2.3,
          name: '主要颜色:68深蓝色,尺码:155/80A/S',
        }, {
          value: 5.1,
          name: '主要颜色:09黑色,尺码:155/80A/S',
        }, {
          value: 2.5,
          name: '主要颜色:14玛瑙红色,尺码:160/84A/M'
        }, {
          value: 3.8,
          name: '主要颜色:58深绿色,尺码:155/80A/S'
        }, {
          value: 13.4,
          name: '主要颜色:46鹅黄色,尺码:160/84A/M'
        }, {
          value: 10.8,
          name: '主要颜色:46鹅黄色,尺码:155/80A/S'
        }],
        itemStyle: {
          emphasis: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }]
    };
    if (option && typeof option === "object") {
      myChart.setOption(option, true);
    }
  };
  myChart();
  // 买家秀sku图片
  function getImg(thumbnails) {
    var href = '';
    if (null != thumbnails) {
      var thumbnailsLength = thumbnails.length;
      if (thumbnailsLength <= 0) {
        href = '<a href="javascript:void(0);" class="dbgj-font-orange">无</a>';
      } else {
        for (var j = 0; j < thumbnailsLength; j++) {
          var thumbnail = thumbnails[j];
          if (null != thumbnail) {
            if (j == 0) {
              var re1 = '<a href="javascript:void(0);" class="dbgj-font-red" onclick="window.open(\'' + thumbnail + ' \')"> ① </a> ';
              href = href + re1;
            } else if (j == 1) {
              var re2 = '<a href="javascript:void(0);" class="dbgj-font-red" onclick="window.open(\'' + thumbnail + ' \')"> ② </a>';
              href = href + re2;
            } else if (j == 2) {
              var re3 = '<a href="javascript:void(0);" class="dbgj-font-red" onclick="window.open(\'' + thumbnail + ' \')"> ③ </a>';
              href = href + re3;
            } else if (j == 3) {
              var re4 = '<a href="javascript:void(0);" class="dbgj-font-red" onclick="window.open(\'' + thumbnail + ' \')"> ④ </a>';
              href = href + re4;
            }
          } else {
            href = '<a href="javascript:void(0);" class="dbgj-font-red">无</a>';
          }
        }
      }
    } else {
      href = '<a href="javascript:void(0);" class="dbgj-font-orange">无</a>';
    }
    return href;
  }
  //sku评价分页
  let feekback = [],
    skuData = [];
  let listContentObj = $('#skuEvaluate-table-body');
  let listItemObj = $('#skuEvaluate-table-item');
  let skuListContentObj = $('#list_content_sku');
  let sukListItemObj = $('#list_item_sku');
  // sku信息请求
  function findPage(productId, type) {
    dbgjObj.loadingOpen();
    ajaxFetch("POST", dbgjBase + "/sku/searchComment", {
      productId: productId,
      type: type
    }, function (res) {
      dbgjObj.loadingClose();
      if (res.code === "1") return;
      if (res.code === "0") {
        if (res.data.feekback.length === 0) {
          Message("SKU评价暂无数据", 3, 4000);
        }

        feekback = res.data.feekback;
        let pageCount = parseInt(
          Math.ceil(feekback.length / 10)
        );
        paging({
          pageCount: pageCount,
          startnum: 1
        });
        //sku
        if (res.data.sku.length === 0) {
          Message("SKU占比暂无数据", 3, 4000);
          return;
        }
        let skuArray = [];
        skuData = res.data.sku;
        let length = skuData.length;
        if (length <= 20) {
          $('#skuPieChart').css("display", ''); //显示饼图
          $('#skuTable').css("display", 'none'); //隐藏列表
          for (let i = 0; i < length; i++) {
            let one = skuData[i];
            let value = one.ratio;
            value = value.replace('%', '');
            let key = one.skuName;
            key = strReplace(key);
            let skuArrayItem = {
              value: value,
              name: key
            };
            skuArray[i] = skuArrayItem;
          }
          let myChart = echarts.init(document.getElementById('skuPieChart'));
          myChart.setOption({
            series: [{
              data: skuArray
            }]
          });
        } else {
          let pageCount = parseInt(
            Math.ceil(length / 5)
          );
          pagingSku({
            productId: productId,
            pageCount: pageCount,
            startnum: 1
          })
        }
      }
    });
  }

  
  // 分页
  function paging(params) {
    const {
      pageCount,
      startnum
    } = params;
    listContentObj.empty();
    let feekbackData = feekback.filter((item, index) => {
      const newIndex = index + 1
      const max = startnum * 5 //末端数据
      const min = max - 5 + 1 //首端数据
      if (newIndex >= min && newIndex <= max) {
        return item
      }
    })
    let length = feekbackData.length;
    for (let i = 0; i < length; i++) {
      let oneData = feekbackData[i];
      let listItem = listItemObj.clone();
      listItem.find('.dataNum').text(i + 1);
      listItem.find('.auctionNumId').text(oneData.auctionNumId);
      proId = oneData.auctionNumId;
      listItem.find('.userNick').text(oneData.userNick);
      // listItem.find('.userStar').text(getStar(oneData.userStar));
      listItem.find('.feedbacktype').text(oneData.feedbacktype);
      let replaceStr = oneData.skuMap;
      let sku = strReplace(replaceStr);
      listItem.find('.skuMap').text(sku);
      listItem.find('.feedbackDate').text(oneData.feedbackDate);
      listItem.find('.rateType').text(oneData.rateType);
      listItem.find('.userphotos').text(oneData.userphotos);
      listItem.find('.feedback').text(oneData.feedback);
      let thumbnails = oneData.thumbnails;
      let img = getImg(thumbnails);
      listItem.find('.thumbnailPhotos').html(img);
      listContentObj.append(listItem);
    }
    Page({
      num: pageCount, //页码数
      startnum: startnum, //指定页码
      elem: $('#pageSkuEvaluate'), //指定的元素
      callback: function (num) { //回调函数
        paging({
          pageCount: pageCount,
          startnum: num
        });
      }
    });
  }
  // sku占比分页
  function pagingSku(params) {
    const {
      productId,
      pageCount,
      startnum
    } = params;
    $('#skuPieChart').css("display", 'none'); //隐藏饼图
    skuListContentObj.empty();
    let skuPageData = skuData.filter((item, index) => {
      const newIndex = index + 1
      const max = startnum * 5 //末端数据
      const min = max - 5 + 1 //首端数据
      if (newIndex >= min && newIndex <= max) {
        return item
      }
    })
    let length = skuPageData.length;
    for (let i = 0; i < length; i++) {
      let oneData = skuPageData[i];
      let listItem = sukListItemObj.clone();
      listItem.find('.dataNum_sku').text(i + 1);
      listItem.find('.auctionNumId_sku').text(productId);
      listItem.find('.type_sku').text(strReplace(oneData.skuName));
      listItem.find('.rate_sku').text(oneData.ratio);
      skuListContentObj.append(listItem);
    }
    $('#skuTable').css("display", ''); //显示列表
    Page({
      num: pageCount, //页码数
      startnum: startnum, //指定页码
      elem: $('#pageSku'), //指定的元素
      callback: function (num) { //回调函数
        pagingSku({
          productId: productId,
          pageCount: pageCount,
          startnum: num
        })
      }
    });
  }
  // sku和买家秀搜索
  $("#sku-buyer-show-search .search-btn").click(function () {
    let pid = $("#sku-input").val();
    if ($.isEmpty(pid)) {
      Message("请先输入商品id或者淘宝链接", 3, 3000);
      return;
    }
    // 商品信息请求
    ajaxFetch("POST", dbgjBase + "/product/detail", {
      productId: pid
    }, function (res) {
      const {
        code,
        data
      } = res;
      if (code === "1") return;
      $("#dialog-content-31 .dbgj-goods-info-img").attr("src", data.item.images[0]);
      $("#dialog-content-31 .dbgj-goods-info-title").text(data.item.title);
      $("#dialog-content-31 .dbgj-goods-info-shop").text(data.seller.shopName);
      $("#dialog-content-31 .dbgj-goods-info-price").text(data.price);
      $("#dialog-content-31 .dbgj-goods-info-buyerCount").text(data.sales);
    });
    // SKU占比评价分析
    findPage(pid, "1");
    // 买家秀
    setBuyerShow(pid);
  });
  // 导出sku占比数据
  $("#derive-skuRatioData-excel").click(function () {
    let pid = $("#sku-input").val();
    if ($.isEmpty(pid)) {
      Message("请先输入商品id或者淘宝链接", 3, 3000);
      return;
    }
    if (skuData.length <= 0) {
      Message("请先获取到数据再导出", 3, 3000);
      return;
    }
    downloadFile("/skuResearch/getExportExcel", {
      productId: pid,
      sku: skuData
    }, "sku占比数据");
  });

  //打包图片
  let thumbnailsArr = [];
  let zipCode = 10;
  let imageSuffix = []; //图片后缀
  // 打包买家秀图片
  $(".zip-buyshow-img").click(function () {
    let num = $(this).attr("data-num");
    if (thumbnailsArr.length === 0) {
      Message('请输入商品ID或链接获取到数据再打包', 3, 3000);
      return
    }
    if (num === "all") {
      thumbnails = thumbnailsArr
    } else {
      num = Number(num);
      thumbnails = thumbnailsArr.filter((item, index) => {
        return index < num
      });
    }
    thumbnails.reverse();
    if (thumbnails !== '') {
      layer.alert('正在采集中，请稍等...', {
        icon: 1,
        skin: 'layer-ext-moon' //该皮肤由layer.seaning.com友情扩展。关于皮肤的扩展规则，去这里查阅
      });
      let zip = new JSZip
      let img = zip.folder("images")
      thumbnails.forEach((v, i) => {
        let suffix = v.substring(v.lastIndexOf("."))
        imageSuffix.push(suffix)
        //转文件对象
        let arr = dbgjObj.getFileResolve(v)
        img.file('买家秀' + i + imageSuffix[i], arr);
      })
      setTimeout(() => {
        zip.generateAsync({
          //接收文件对象
          type: "blob"
        }).then(function (content) {
          // see FileSaver.js
          Message("采集买家秀完毕");
          saveAs(content, "买家秀.zip");
        });
      }, 100)
    } else {
      MessageBox("买家秀", '打包图片失败');
    }
    //倒计时
    // let packTime = setInterval(() => {
    //   zipCode--;
    //   if (zipCode == 0) {
    //     zipCode = 10
    //     layer.alert('采集买家秀完毕', {
    //       icon: 1,
    //       time: 5000,
    //       skin: 'layer-ext-moon' //该皮肤由layer.seaning.com友情扩展。关于皮肤的扩展规则，去这里查阅
    //     });
    //     clearInterval(packTime);
    //   }
    // }, 1000)
  });

  function setBuyerShow(pid) {
    // SKU买家秀
    ajaxFetch("POST", dbgjBase + "/sku/getAllBuyers", {
      productId: pid
    }, function (res) {
      thumbnailsArr = res.data.thumbnails;
      let num = res.data.thumbnails.length;
      num = Number(num);
      if (num > 200) {
        $(".zip-buyshow-img").show();
      } else if (num > 100 && num < 200) {
        $(".zip-buyshow-img").show();
      } else if (num > 50 && num < 100) {
        $(".zip-buyshow-img").each(function () {
          if ($(this).attr("data-num") == "200") {
            $(this).hide();
          } else {
            $(this).show();
          }
        });
      } else if (num <= 50 && num > 0) {
        $(".zip-buyshow-img").each(function (index) {
          if ($(this).attr("data-num") == "200" || $(this).attr("data-num") == "100") {
            $(this).hide();
          } else {
            $(this).show();
          }
        });
      } else if (num <= 0) {
        $(".zip-buyshow-img").hide();
      }
    });

  }
  // 导出sku评论数据
  $("#derive-skuEvaluate-excel").click(function () {
    let pid = $("#sku-input").val();
    if ($.isEmpty(pid)) {
      Message("请先输入商品id或者淘宝链接", 3, 3000);
      return;
    }
    if (feekback.length === 0) {
      Message("请先获取到数据再导出", 3, 3000);
      return;
    }
    downloadFile("/sku/exportExcel", {
      productId: pid,
      type: "1"
    }, "SKU评论数据-");
  });

  // 采集问大家自动获取
  $("#dialog-content-33 .one-auto-btn").click(function () {
    $("#askQuestionInput").val(dbgjObj.getCurrentPageId);
  });

  let questionWords = [],
    questionFeeds = [],
    questionWordsType = "全部";
  let questionListContentObj = $("#question_list_content");
  // let questionListItemObj = $("#question_list_item");
  // 问大家分页
  function askQuestionPage(type, pageNumber) {
    if (questionWordsType !== type) {
      pageNumber = 1
    }
    questionListContentObj.empty();
    // 筛选相同的问题
    let QuestionFeeds = [];
    if (type === "全部") {
      QuestionFeeds = questionFeeds;
    } else {
      QuestionFeeds = questionFeeds.filter((item) => {
        if (item.title.indexOf(type) !== -1) {
          return item;
        }
      });
    }

    // 分页
    let fiterQuestionFeeds = QuestionFeeds.filter((item, index) => {
      const newIndex = index + 1
      const max = pageNumber * 5 //末端数据
      const min = max - 5 + 1 //首端数据
      if (newIndex >= min && newIndex <= max) {
        return item
      }
    })
    let pageCount = parseInt(
      Math.ceil(QuestionFeeds.length / 5)
    );
    for (let i = 0; i < fiterQuestionFeeds.length; i++) {
      let oneData = fiterQuestionFeeds[i];
      let subFeeds = oneData.subFeeds.filter((item, index) => {
        return index < 3
      });
      let title = oneData.title;
      let gmtCreate = dbgjObj.timestampToDate(oneData.gmtCreate, "onlyDate");
      for (let j = 0; j < subFeeds.length; j++) {
        let twoData = subFeeds[j];
        if (twoData.userScore === null) {
          twoData.userScore = ""
        }
        if (subFeeds.length > 1) {
          if (j === 0) {
            let questionListItemHtml = `
            <tr id="question_list_item">
              <td rowspan=${subFeeds.length} class="gmtCreate">${gmtCreate}</td>
              <td rowspan=${subFeeds.length} class="title">${title}</td>
              <td class="subTitle">${twoData.title}</td>
              <td class="subGmtCreate">${dbgjObj.timestampToDate(twoData.gmtCreate, "onlyDate")}</td>
              <td class="subUserNick">${dbgjObj.userNickFilter(twoData.userNick)}</td>
              <td class="subUserScore" style="display:none">${twoData.userScore}</td>
            </tr>`
            questionListContentObj.append(questionListItemHtml);
          } else {
            let questionListItemHtml = `
            <tr id="question_list_item">
              <td rowspan=${subFeeds.length} class="gmtCreate" style="display:none">${gmtCreate}</td>
              <td rowspan=${subFeeds.length} class="title" style="display:none">${title}</td>
              <td class="subTitle">${twoData.title}</td>
              <td class="subGmtCreate">${dbgjObj.timestampToDate(twoData.gmtCreate, "onlyDate")}</td>
              <td class="subUserNick">${dbgjObj.userNickFilter(twoData.userNick)}</td>
              <td class="subUserScore" style="display:none">${twoData.userScore}</td>
            </tr>`
            questionListContentObj.append(questionListItemHtml);
          }
        } else {
          let questionListItemHtml = `
            <tr id="question_list_item">
              <td class="gmtCreate">${gmtCreate}</td>
              <td class="title">${title}</td>
              <td class="subTitle">${twoData.title}</td>
              <td class="subGmtCreate">${dbgjObj.timestampToDate(twoData.gmtCreate, "onlyDate")}</td>
              <td class="subUserNick">${dbgjObj.userNickFilter(twoData.userNick)}</td>
              <td class="subUserScore" style="display:none">${twoData.userScore}</td>
            </tr>`
          questionListContentObj.append(questionListItemHtml);
        }
      }
    }
    Page({
      num: pageCount, //页码数
      startnum: pageNumber, //指定页码
      elem: $('#askQuestion-page'), //指定的元素
      callback: function (num) { //回调函数
        askQuestionPage(type, num);
      }
    });
  }
  // 采集问大家搜索
  $("#dialog-content-33 .search-btn").click(function () {
    let pid = $("#askQuestionInput").val();
    if ($.isEmpty(pid)) {
      Message("请先输入商品id或者淘宝链接", 3, 3000);
      return;
    }
    // 商品信息请求
    ajaxFetch("POST", dbgjBase + "/product/detail", {
      productId: pid
    }, function (res) {
      const {
        code,
        data
      } = res;
      if (code === "1") return;
      $("#dialog-content-33 .dbgj-goods-info-img").attr("src", data.item.images[0]);
      $("#dialog-content-33 .dbgj-goods-info-title").text(data.item.title);
      $("#dialog-content-33 .dbgj-goods-info-shop").text(data.seller.shopName);
      $("#dialog-content-33 .dbgj-goods-info-price").text(data.price);
      $("#dialog-content-33 .dbgj-goods-info-buyerCount").text(data.sales);
    });
    // 问大家请求
    dbgjObj.loadingOpen();
    ajaxFetch("POST", dbgjBase + "/product/questionnaire", { productId: pid }, function (res) {
      dbgjObj.loadingClose();
      const {
        code,
        data
      } = res;
      if (code === "1") return;
      if (data.questionWords.length === 0 && data.feeds.length === 0) {
        Message("暂无数据", 3, 3000);
        $("#questionWords_type_list").empty();
        return;
      }
      questionWords = ["全部", ...data.questionWords];
      questionWordsType = "全部";
      $("#questionWords_type_list").empty();
      for (let i = 0; i < questionWords.length; i++) {
        let name = questionWords[i];
        if (name === "全部") {
          $("#questionWords_type_list").append(`<span class="dbgj-primary-btn dbgj-mr-10 dbgj-mb-10 active">${name}</span>`);
        } else {
          $("#questionWords_type_list").append(`<span class="dbgj-primary-btn dbgj-mr-10 dbgj-mb-10">${name}</span>`);
        }
      }
      // 过滤掉空的问题
      questionFeeds = data.feeds.filter(item => {
        if (item.title) {
          return item
        }
      });
      askQuestionPage("全部", 1);
    });

  });
  // 绑定问大家关键词
  $("#questionWords_type_list").on("click", ".dbgj-primary-btn", function () {
    $(this).addClass("active").siblings(".dbgj-primary-btn").removeClass("active");
    let text = $(this).text();
    questionWordsType = text;
    askQuestionPage(text, 1);
  });
  // 导出问大家的数据
  $("#derive-ask-excel").click(function () {
    let pid = $("#askQuestionInput").val();
    if ($.isEmpty(pid)) {
      Message("请先输入商品id或者淘宝链接", 3, 3000);
      return;
    }
    downloadFile("/product/questionnaire/getExportExcel", {
      productId: pid
    }, "采集问大家数据-");
  });
  // 详情页直接打开获取
  if (autoGetIndex == 31) {
    $("#sku-buyer-show-search .one-auto-btn").click();
    $("#sku-buyer-show-search .search-btn").click();
  } else if (autoGetIndex == 33){
    $("#dialog-content-33 .one-auto-btn").click();
    $("#dialog-content-33 .search-btn").click();
  }
}
// 商家助手
function merchantAssistantInit() {
  // 极速打标签
  $("#crowdTagSearch").click(function () {
    let fromPrice = $("#dialog-content-41").find("#fromPrice").val();
    let toPrice = $("#dialog-content-41").find("#toPrice").val();
    let keyword = $("#dialog-content-41").find("#crowdTagKeyword").val();
    if ($.isEmpty(fromPrice)) {
      Message("请先输入最低价格", 3, 3000);
      return;
    }
    if ($.isEmpty(toPrice)) {
      Message("请先输入最高价格", 3, 3000);
      return;
    }
    if ($.isEmpty(keyword)) {
      Message("请先输入关键词", 3, 3000);
      return;
    }
    fromPrice = $.trim(fromPrice);
    toPrice = $.trim(toPrice);
    // 打标签请求
    ajaxFetch("POST", dbgjBase + "/crowd/label", {
      fromPrice,
      toPrice,
      keyword
    }, function (res) {
      const {
        data,
        code,
        msg
      } = res;
      if (code === "1") {
        Message(msg, 3, 3000);
        return;
      }
      Message("打标签成功, 请使用淘宝APP扫码查看");
      $("#crowdTagQrCode").empty();
      $("#crowdTagQrCode").qrcode({
        width: 200,
        height: 200,
        text: data
      });
      $("#crowdTagQrCode").siblings("img").hide();
    })
  });
  // 卡首页查询切换
  $("#dialog-content-42 .dbgj-radio-button").click(function () {
    const index = $(this).index()
    $('#dialog-content-42 .card-index').eq(index).removeClass('dbgj-hide').siblings(".card-index").addClass("dbgj-hide");
    $(this).addClass("selected").siblings(".dbgj-radio-button").removeClass("selected");
  });
  // 卡关键词首页自动获取
  $("#card_keyword_box").find(".auto-btn").click(function () {
    let pid = dbgjObj.getCurrentPageId();
    $("#cardIndexIdInput").val(pid);
    // 商品信息请求
    ajaxFetch("POST", dbgjBase + "/product/detail", {
      productId: pid
    }, function (res) {
      const {
        code,
        data
      } = res;
      if (code === "1") return;
      $("#card_keyword_box .dbgj-goods-info-img").attr("src", data.item.images[0]);
      $("#card_keyword_box .dbgj-goods-info-title").text(data.item.title);
      $("#card_keyword_box .dbgj-goods-info-shop").text(data.seller.shopName);
      $("#card_keyword_box .dbgj-goods-info-price").text(data.price);
      $("#card_keyword_box .dbgj-goods-info-buyerCount").text(data.sales);
    });
  });
  // 卡关键词输入框变化获取商品id
  $('#cardIndexIdInput').bind('input propertychange', function () {
    let pid = $(this).val();
    if ($.isEmpty(pid)) {
      return;
    }
    // 商品信息请求
    ajaxFetch("POST", dbgjBase + "/product/detail", { productId: pid }, function (res) {
      const { code, data } = res;
      if (code === "1") return;
      $("#card_keyword_box .dbgj-goods-info-img").attr("src", data.item.images[0]);
      $("#card_keyword_box .dbgj-goods-info-title").text(data.item.title);
      $("#card_keyword_box .dbgj-goods-info-shop").text(data.seller.shopName);
      $("#card_keyword_box .dbgj-goods-info-price").text(data.price);
      $("#card_keyword_box .dbgj-goods-info-buyerCount").text(data.sales);
    });
  });
  // 卡关键词首页
  $("#card_keyword_box").find(".search-btn").click(function () {
    let pid = $("#cardIndexIdInput").val();
    let keyword = $("#cardIndexKeywordInput").val();
    if ($.isEmpty(pid)) {
      Message("请先输入商品id或者链接", 3, 3000);
      return;
    }
    if ($.isEmpty(keyword)) {
      Message("请先输入关键词", 3, 3000);
      return;
    }
    // 卡首页请求
    ajaxFetch("POST", dbgjBase + "/card/res", {
      productId: pid,
      keyword: keyword
    }, function (result) {
      const {
        data,
        code,
        msg
      } = result;
      if (code === "1") {
        Message(msg, 3, 3000);
        return;
      }
      $("#cardKeywordQrcode").empty();
      $("#cardKeywordQrcode").qrcode({
        width: 200,
        height: 200,
        text: data.res
      });
      $("#cardKeywordQrcode").siblings("img").hide();
    });
  });

  // 卡手淘首页自动获取
  $("#card_handTao_box").find(".auto-btn").click(function () {
    let pid = dbgjObj.getCurrentPageId();
    $("#cardHandTaoId").val(pid);
    // 商品信息请求
    ajaxFetch("POST", dbgjBase + "/product/detail", { productId: pid }, function (res) {
      const {
        code,
        data
      } = res;
      if (code === "1") return;
      $("#card_handTao_box .dbgj-goods-info-img").attr("src", data.item.images[0]);
      $("#card_handTao_box .dbgj-goods-info-title").text(data.item.title);
      $("#card_handTao_box .dbgj-goods-info-shop").text(data.seller.shopName);
      $("#card_handTao_box .dbgj-goods-info-price").text(data.price);
      $("#card_handTao_box .dbgj-goods-info-buyerCount").text(data.sales);
    });
  });
  // 卡手淘输入框变化获取商品id
  $('#cardHandTaoId').bind('input propertychange', function () {
    let pid = $(this).val();
    if ($.isEmpty(pid)) {
      return;
    }
    // 商品信息请求
    ajaxFetch("POST", dbgjBase + "/product/detail", { productId: pid }, function (res) {
      const { code, data } = res;
      if (code === "1") return;
      $("#card_handTao_box .dbgj-goods-info-img").attr("src", data.item.images[0]);
      $("#card_handTao_box .dbgj-goods-info-title").text(data.item.title);
      $("#card_handTao_box .dbgj-goods-info-shop").text(data.seller.shopName);
      $("#card_handTao_box .dbgj-goods-info-price").text(data.price);
      $("#card_handTao_box .dbgj-goods-info-buyerCount").text(data.sales);
    });
  });
  // 卡手淘首页
  $("#card_handTao_box").find(".search-btn").click(function () {
    let pid = $("#cardHandTaoId").val();
    let type = $("#cardHandTao_type option:selected").val();
    if ($.isEmpty(pid)) {
      Message("请先输入商品id或者链接", 3, 3000);
      return;
    }
    if ($.isEmpty(type)) {
      Message("请先选择类型", 3, 3000);
      return;
    }
    // 卡首页请求
    ajaxFetch("POST", dbgjBase + "/card/flow", {
      productId: pid,
      type: type
    }, function (result) {
      const {
        data,
        code,
        msg
      } = result;
      if (code === "1") {
        Message(msg, 3, 3000);
        return;
      }
      $("#cardHandTaoQrcode").empty();
      $("#cardHandTaoQrcode").qrcode({
        width: 200,
        height: 200,
        text: data.res
      });
      $("#cardHandTaoQrcode").siblings("img").hide();
    });
  });

  // 实时搜索下拉选择框
  let timeId = null;
  let realTimePage = 1;
  let realTimeType = 2;
  let realTimeProductHtml = ''

  function getKeywordSearchInfo(value) {
    ajaxFetch("POST", dbgjBase + "/realtime/search", {
      keyword: value
    }, function (res) {
      $("#realTimeRank_xiala").empty();
      $('.loading-select-img').hide();
      const {
        code,
        data,
        msg
      } = res;
      if (code === "1") {
        Message(msg, 3, 3000)
        return;
      }
      if (data === null) {
        Message("服务器出错", 3, 3000)
        return;
      }
      data.reverse();
      for (let i in data) {
        $("#realTimeRank_xiala").append(`<li><span class="match-word">${data[i]}</span></li>`);
      }
    });
  }
  // 搜索实时查排名
  function getRealTimeProductInfo(keyword, page, type) {
    let params = {
      keyword: keyword,
      page: page,
      type: type
    };
    dbgjObj.loadingOpen();

    ajaxFetch("POST", dbgjBase + "/realtime/info", params, function (res) {
      dbgjObj.loadingClose();
      let code = res.code,
        data = res.data,
        msg = res.msg;
      if (code === "1") {
        Message(msg, 3, 3000);
        return;
      }
      let listData = res.data
      if (page > 1) {
        listData.concat(res.data)
      } else {
        listData = data;
      }
      $("#dialog-content-43").find('.loading-img').hide();
      $('#load-more').hide();
      $("#dialog-content-43").find(".realTime-content-box").empty();
      for (let i = 0; i < listData.length; i++) {
        let item = listData[i];
        realTimeProductHtml += `<div class="realTime-content cp">
                    <div class="realTime-content-left">
                        <img src="${item.pic}" alt="">
                    </div>
                    <div class="realTime-content-right">
                        <div class="realTime-content-right-title title">${item.title}</div>
                        <div class="realTime-content-right-price">
                            <span class="dbgj-mr-10 dbgj-font-red showPrice">￥${item.showPrice}</span>
                            <del class="dbgj-font14 dbgj-font-gray price">￥${item.price}</del>
                        </div>
                        <div class="realTime-content-right-address">
                            <span class="yunfei">${item.yunfei}</span>
                            <span class="buyCount">${item.buyCount}人付款</span>
                            <span class="area">${item.area}</span>
                            <p class="nick" style="display: none">${item.nick}</p>
                            <p class="dsr" style="display: none">${item.dsr}</p>
                            <p class="skuCount" style="display: none">${item.skuCount}</p>
                            <p class="remark" style="display: none">${item.remark}</p>
                            <p class="category" style="display: none">${item.category}</p>
                            <p class="sales" style="display: none"><span></span>${item.sales}</p>
                            <p class="itemId" style="display: none">${item.itemId}</p>
                        </div>
                    </div>
                </div>`;
      }
      $("#dialog-content-43").find(".realTime-content-box").html(realTimeProductHtml);
      $('.realTime-content-box').show();
    })
  }
  /*商品参与淘客*/
  function getTaoke(itemId) {

    let parm = {
      itemId: itemId
    };

    ajaxFetch("POST", dbgjBase + "/tbk", parm, function (res) {

      // if(!res) {

      // 	layer.close(layerIndex);
      // } else {				
      // 	layer.close(layerIndex);
      // }
      // layer.close(layerIndex);
      if (res.code == 0) {
        getCurrentUserInfo();
        $(".tkTip").css('display', 'none');
        $(".tk_info").css('display', '');
        let data = res.data;
        $("#realTime-table_tk_1").text(data.couponPrice);
        $("#realTime-table_tk_2").text(data.couponRemainCount);
        $("#realTime-table_tk_3").text(data.couponSendCount);
        $("#realTime-table_tk_4").text(data.price);
        $("#realTime-table_tk_5").text(data.priceAfterCoupon);
        $("#realTime-table_tk_6").text(data.tkTotalSales);
        $("#realTime-table_tk_7").text(data.tkCommissionAmount);
        $("#realTime-table_tk_8").text(data.calTkRate);
        $("#realTime-table_tk_12").text('下架时间:' + "无");
        $("#realTime-table_downTime").text("无");
      } else {
        $("#realTime_taoke_info .tk_info").css('display', 'none');
        $("#realTime_taoke_info .tkTip").css('display', '');
      }
    }, function (res) {

    });
  }
  // 输入框变化事件
  $('#realTimeRank').bind('input propertychange', function () {
    let value = $(this).val();
    if (!value.trim()) {
      $('#suggest-container').hide();
      $('.loading-select-img').hide();
      return
    }
    $('#suggest-container').show();
    $('.loading-select-img').show();
    clearTimeout(timeId);
    timeId = setTimeout(function () {
      if (value) {
        getKeywordSearchInfo(value);
      }
    }, 500);
  });
  // 实时查排名搜索
  $("#dialog-content-43").find(".search-btn").click(function () {
    let keyword = $("#realTimeRank").val();
    if ($.isEmpty(keyword)) {
      Message("请先输入关键词", 3, 3000);
      return;
    }
    realTimePage = 1;
    $('.loading-img').show()
    $('#suggest-container').hide();
    keyword = keyword.replace(/[ ]/g, '');
    realTimeType = 2;
    $(".sort-tab-first").addClass("active");
    $(".sort-tab-second").removeClass("active");
    realTimeProductHtml = "";
    getRealTimeProductInfo(keyword, realTimePage, realTimeType);
  });
  //滚动条到底部
  $("#dialog-content-43 .realTime-content-box").scroll(function () {
    let viewH = $(this).height(), //可见高度
      contentH = $(this).get(0).scrollHeight, //内容高度
      scrollTop = $(this).scrollTop(); //滚动高度
    //if(contentH - viewH - scrollTop <= 100) { //到达底部100px时,加载新内容
    if (scrollTop / (contentH - viewH) >= 0.95) { //到达底部100px时,加载新内容
      // 这里加载数据..
      $('#load-more').show()
    } else {
      $('#load-more').hide()
    }
  });
  //分页功能，加载更多
  $('#load-more').click(function () {
    $('.loading-img').show();
    let value = $("#realTimeRank").val();
    realTimePage++;
    getRealTimeProductInfo(value, realTimePage, realTimeType);
  });
  //tab栏切换样式
  $('#realTimeTank-sort-tab>div').click(function () {
    let index = $(this).index();
    let value = $('#realTimeRank').val();
    value = value.replace(/[ ]/g, '');
    if (index == 0) { //综合查询
      realTimeType = 2;
      realTimeProductHtml = "";
      $('.loading-img').show()
      getRealTimeProductInfo(value, realTimePage, realTimeType);
    } else if (index == 1) { //销量查询
      realTimeType = 3;
      realTimeProductHtml = "";
      $('.loading-img').show()
      getRealTimeProductInfo(value, realTimePage, realTimeType);
    }
    if (index == 2) {
      return;
    }
    $(this).addClass('active').siblings().removeClass('active');
  });
  /*input 框赋值*/
  $("#realTimeRank_xiala").on("click", "li", function () {
    realTimePage = 1
    $('.loading-img').show();
    $('.realTime-content-box').hide();
    $('#suggest-container').hide();
    var value = $(this).text();
    value = value.replace(/[ ]/g, '');
    $('#realTimeRank').val(value);
    $('#suggest-container').hide();
    realTimeType = 2;
    $(".sort-tab-first").addClass("active");
    $(".sort-tab-second").removeClass("active");
    realTimeProductHtml = ''; //点击按钮清空之前缓存
    getRealTimeProductInfo(value, realTimePage, realTimeType);
  });
  /*左边信息右边展示*/
  $(".realTime-content-box-more").on("click", ".realTime-content", function () {
    let title = $(this).find(".title").text();
    let showPrice = $(this).find(".showPrice").text();
    let price = $(this).find(".price").text();
    let yunfei = $(this).find(".yunfei").text();
    let buyCount = $(this).find(".buyCount").text();
    let area = $(this).find(".area").text();
    let nick = $(this).find(".nick").text();
    let skuCount = $(this).find(".skuCount").text();
    let img = $(this).find('.realTime-content-left>img')[0].src;
    let remark = $(this).find(".remark").text();
    let category = $(this).find(".category").text();
    let dsr = $(this).find(".dsr").text();
    let sales = $(this).find(".sales").text();
    let itemId = $(this).find(".itemId").text();

    /*属性*/
    $("#realTime-table_buyCount").text("今天实付款人数：" + buyCount);
    let arr = remark.split(',')
    let newHtml = ''
    if (remark == "") {
      newHtml += "<span>" + "无" + "</span>";
      $('#realTime-table_attr').html(newHtml);
    } else {
      arr.forEach(function (value, i) {
        if (value) {
          newHtml += "<span>" + value + "</span>";
          $('#realTime-table_attr').html(newHtml);
        }
      })
    }
    /*dsr*/
    let dsrArr = dsr.split(';');
    if (dsrArr.length > 0) {
      dsrArr.forEach(function (value, j) {
        if (value) {
          let background = "#1890ff";
          if (j == 0) {
            if (value.indexOf("低") > 0) {
              background = "rgb(35, 210, 189)";
            } else if (value.indexOf("平") > 0) {
              background = "rgb(153, 153, 153)";
            } else if (value.indexOf("高") > 0) {
              background = "rgb(255, 80, 0)";
            }
            $('#realTime-table_>span').css('color', background);
            $('#realTime-table_baobei>span').html(value);
          } else if (j == 1) {
            if (value.indexOf("低") > 0) {
              background = "rgb(35, 210, 189)";
            } else if (value.indexOf("平") > 0) {
              background = "rgb(153, 153, 153)";
            } else if (value.indexOf("高") > 0) {
              background = "rgb(255, 80, 0)";
            }
            $('#realTime-table_maijia>span').css('color', background);
            $('#realTime-table_maijia>span').html(value);
          } else if (j == 2) {
            if (value.indexOf("低") > 0) {
              background = "rgb(35, 210, 189)";
            } else if (value.indexOf("平") > 0) {
              background = "rgb(153, 153, 153)";
            } else if (value.indexOf("高") > 0) {
              background = "rgb(255, 80, 0)";
            }
            $('#realTime-table_wuliu>span').css('color', background);
            $('#realTime-table_wuliu>span').html(value);
          }
        }
      })
    }

    $("#realTimeItemInfo").find(".realTime-content-right-title").text(title);
    $("#realTimeItemInfo").find(".showPrice").text(showPrice);
    $("#realTimeItemInfo").find(".price").text(price);
    $("#realTimeItemInfo").find(".yunfei").text(yunfei);
    $("#realTimeItemInfo").find(".buyCount").text(buyCount);
    $("#realTimeItemInfo").find(".area").text(area);
    if (!category) {
      //空
      $("#realTime-table_category").text("无");
    } else {
      $("#realTime-table_category").text(category);
    }
    if (!nick) {
      //空
      $("#realTime-table_nick").text("无");
    } else {
      $("#realTime-table_nick").text(nick);
    }
    $("#realTime-table_skuCount").text(skuCount);
    if (null == sales) {
      $("#realTimeItemInfo").find(".sales").text("");
    } else {
      $("#realTimeItemInfo").find(".sales").text(sales);
    }
    $("#realTimeItemInfo").find('.realTime-content-left>img').attr('src', img);
    getTaoke(itemId);
  });

  function getLanhaiLevData(level, parentId) {
    ajaxFetch("POST", dbgjBase + "/lanhaiCategory/all", {
      level: level,
      parentId: parentId
    }, function (res) {
      const {
        code,
        data
      } = res;
      if (code === "1") return;
      if (level == "2") {
        $("#lanhai_second_select").empty();
        if (data.length !== 0) {
          for (let i in data) {
            let oneObj = data[i];
            $('#lanhai_second_select').append('<option value="' + oneObj.id + '">' + oneObj.name + '</option>');
          }
        }
      }
      if (level == "3") {
        $("#lanhai_third_select").empty();
        if (data.length !== 0) {
          for (let i in data) {
            let oneObj = data[i];
            $('#lanhai_third_select').append('<option value="' + oneObj.id + '">' + oneObj.name + '</option>');
          }
        }
      }
    });
  }
  // 类目蓝海词
  // 获取二级
  $("#lanhai_first_select").on("change", function () {
    let parentId = $(this).find("option:selected").val();
    $(this).find("option").each(function () {
      if ($(this).text() === "一级类目") {
        $(this).remove();
      }
    });
    $("#lanhai_second_select").empty();
    $("#lanhai_third_select").empty();
    getLanhaiLevData("2", parentId)
  });
  // 获取三级
  $("#lanhai_second_select").on("change", function () {
    let parentId = $(this).find("option:selected").val();
    $("#lanhai_third_select").empty();
    getLanhaiLevData("3", parentId)
  });
  // 蓝海词搜索
  let levelSecond = null,
    levelFirst = null,
    levelThirdm = null
  let lanhaiHotCheck = true
  let lanhaiGoodsCheck = true
  let lanhaiCheck = true
  let lanhaiPdSort = ''
  let lanhaiRqSort = ''
  let lanhaiSort = ''
  let lanHaiListContentObj = $("#lanhai_list_content");
  let lanHaiListItemObj = $("#lanhai_list_item");

  function getLanhaiPageData(params) {
    let first = $("#lanhai_first_select").find("option:selected").text();
    let second = $("#lanhai_second_select").find("option:selected").text();
    let thrid = $("#lanhai_third_select").find("option:selected").text();
    params['levelFirst'] = first;
    params['levelSecond'] = second;
    params['levelThirdm'] = thrid;
    lanhaiPdSort = params.pdSort
    lanhaiRqSort = params.rqSort
    lanhaiSort = params.sort
    dbgjObj.loadingOpen();
    ajaxFetch("POST", dbgjBase + "/lanhaiKeword/find", params, function (res) {
      dbgjObj.loadingClose();
      if (res.code == '0') {
        let data = res.data;
        lanHaiListContentObj.empty();
        let lanhaiPageData = data.filter((item, index) => {
          const newIndex = index + 1
          const max = params.page * 10 //末端数据
          const min = max - 10 + 1 //首端数据
          if (newIndex >= min && newIndex <= max) {
            return item
          }
        })
        let pageCount = parseInt(
          Math.ceil(data.length / 10)
        );
        for (let i = 0; i < lanhaiPageData.length; i++) {
          let oneData = lanhaiPageData[i];
          let listItem = lanHaiListItemObj.clone();
          listItem.css('display', '');
          listItem.attr('id', '');
          listItem.find('.sortNo').text(i + 1);
          listItem.find('.keyword').text(oneData.keyword);
          listItem.find('.seIpvUvHits').text(oneData.seipvUvHits);
          listItem.find('.clickRate').text(oneData.clickRate);
          listItem.find('.tmClickRatio').text(oneData.tmClickRatio);
          listItem.find('.onlineGoodsCnt').text(oneData.onlineGoodsCnt)
          listItem.find('.payConvRate').text(oneData.payConvRate);
          listItem.find('.lanHai').text(oneData.lanHai);
          lanHaiListContentObj.append(listItem);
        }
        Page({
          num: pageCount, //页码数
          startnum: params.page, //指定页码
          elem: $('#lanhai-page'), //指定的元素
          callback: function (num) { //回调函数
            params.page = num;
            getLanhaiPageData(params);
          }
        });
      }
    });
  }
  $("#dialog-content-44 .search-btn").click(function () {
    let parentId = $("#lanhai_first_select").find("option:selected").val();
    if ($.isEmpty(parentId)) {
      Message("请先选择一级类目", 3, 3000);
      return
    }
    levelFirst = $("#lanhai_first_select").find("option:selected").text();
    levelSecond = $("#lanhai_second_select").find("option:selected").text();
    levelThirdm = $("#lanhai_third_select").find("option:selected").text();
    let params = {};
    if (levelFirst) {
      params.levelFirst = levelFirst;
    }
    if (levelSecond) {
      params.levelSecond = levelSecond;
    }
    if (levelThirdm) {
      params.levelThirdm = levelThirdm
    }
    params.page = 1
    getLanhaiPageData(params);
  });
  //搜索人气排序
  $('.dbgj-sort-table').on('click', '#renQiSort>.cp', function () {
    $(this).addClass('active');
    $(this).siblings().removeClass('active');
    if (lanhaiHotCheck) {
      //升
      getLanhaiPageData({
        page: 1,
        rqSort: 'desc'
      })
      lanhaiHotCheck = false
    } else {
      //降
      getLanhaiPageData({
        page: 1,
        rqSort: 'asc'
      })
      lanhaiHotCheck = true
    }
  })
  //商品数量排序
  $('.dbgj-sort-table').on('click', '#productSort>.cp', function () {
    $(this).addClass('active');
    $(this).siblings().removeClass('active');
    if (lanhaiGoodsCheck) {
      //升
      getLanhaiPageData({
        page: 1,
        pdSort: 'desc'
      })
      lanhaiGoodsCheck = false
    } else {
      //降
      getLanhaiPageData({
        page: 1,
        pdSort: 'asc'
      })
      lanhaiGoodsCheck = true
    }
  })
  //搜索人气排序
  $('.dbgj-sort-table').on('click', '#lanHaiSort>.cp', function () {
    $(this).addClass('active');
    $(this).siblings().removeClass('active');
    if (lanhaiCheck) {
      //升
      getLanhaiPageData({
        page: 1,
        sort: 'desc'
      })
      lanhaiCheck = false
    } else {
      //降
      getLanhaiPageData({
        page: 1,
        sort: 'asc'
      })
      lanhaiCheck = true
    }
  })
  // 导出蓝海词
  $("#derive_lanhai_excel").click(function() {
    let first = $("#lanhai_first_select").find("option:selected").text();
    let second = $("#lanhai_second_select").find("option:selected").text();
    let thrid = $("#lanhai_third_select").find("option:selected").text();
    const opt = {
      levelFirst:first,
      levelSecond:second,
      levelThirdm:thrid,
      pdSort:lanhaiPdSort,
      rqSort:lanhaiRqSort,
      sort:lanhaiSort,
    }
    downloadFile('/lanhai/getExportExcel',opt,'蓝海词')
  })
  // 行业销售标杆自动获取
  $("#dialog-content-45 .one-auto-btn").click(function () {
    $("#industry_sales_input").val(dbgjObj.getCurrentPageId);
  });
  let industryListContentObj = $('#industry_list_content');
  let industryListItemObj = $('#industry_list_item');

  function industryFindPage(params) {
    industryListItemObj.remove();
    dbgjObj.loadingOpen();
    ajaxFetch("POST", dbgjBase + "/qlyTop/getIndustryData", params, function (res) {
      dbgjObj.loadingClose()
      const {
        data,
        code
      } = res
      if (data.status == 200) {
        industryListContentObj.empty();
        for (var i = 0; i < data.rows.length; i++) {
          var oneData = data.rows[i]
          let listItem = industryListItemObj.clone();
          listItem.css('display', '');
          listItem.attr('id', '');
          listItem.find('.order').text(oneData.rank);
          listItem.find('img').attr('src', oneData.pic);
          listItem.find('.aTitle').text(oneData.name).attr('href', oneData.url);
          listItem.find('.category').text(oneData.category);
          listItem.find('.price').text(oneData.price);
          listItem.find('.good_rate').text((oneData.good_rate * 100).toFixed(2) + '%');
          listItem.find('.score').text(oneData.score);
          listItem.find('.t-img').attr('href', oneData.url);
          listItem.find('.rankChange').text(oneData.rank_diff);
          industryListContentObj.append(listItem);
        }
        Page({
          num: data.pages, //页码数
          startnum: data.page, //指定页码
          elem: $('#Industry-page'), //指定的元素
          callback: function (num) { //回调函数
            params.page = num;
            industryFindPage(params)
          }
        });
      }
    });
  }
  // 行业销售标杆
  let industry_sales_page = 1;
  $("#dialog-content-45 .search-btn").click(function () {
    let productId = $("#industry_sales_input").val();
    if ($.isEmpty(productId)) {
      Message("请先输入商品id或者淘宝链接", 3, 3000);
      return;
    }
    let reg = /^\d+$/;
    if (productId.length < 5) {
      layer.alert("请输入正确商品id或者链接")
      return;
    }
    if (!reg.test(productId)) { //不是数字
      if (productId.indexOf("https") == -1 && productId.indexOf("http") == -1) {
        MessageBox("行业销售标杆", "请输入正确商品id或者链接");
        return;
      }
    } else {
      productId = 'http://item.taobao.com/item.htm?id=' + productId;
    }
    industry_sales_page = 1;
    industryFindPage({
      productId: productId,
      page: 1
    });
  });


  // 秒变手淘自动获取
  $("#dialog-content-46").find(".one-auto-btn").click(function () {
    $("#handTaoInput").val(dbgjObj.getCurrentPageId);
  });
  // 秒变
  $("#dialog-content-46").find(".search-btn").click(function () {
    let id = $("#handTaoInput").val();
    let reg = new RegExp('[?&]id=([^&#]+)');
    let query = id.match(reg);
    id = query ? query[1] : id;
    if ($.isEmpty(id)) {
      Message("请先获取商品id或者链接", 3, 3000);
      return;
    }
    let iframeUrl = dbgjObj.isTmall() ? `https://detail.m.tmall.com/item.htm?id=${id}` : `https://h5.m.taobao.com/awp/core/detail.htm?id=${id}`;
    let iframe = document.getElementById("dbgj-handTao-iframe");
    iframe.setAttribute("src", iframeUrl);
    let iframeBox = document.getElementById("handTao-iframe-box");
    if (iframe.attachEvent) { // 兼容IE写法
      iframe.attachEvent("onload", function () {
        // iframe加载完成后要进行的操作
        iframeBox.style.cssText = "width: 435px";
      })
    } else {
      iframe.onload = function () {
        // iframe加载完成后要进行的操作
        iframeBox.style.cssText = "width: 435px";
      }
    }
  });
}

// 重新请求详情页的接口
function loginAfterInit() {
  getCurrentUserInfo();
  // 在详情页再触发
  let detailPageNode = document.querySelector('.tb-key')
  if (detailPageNode) {
    // 详情页工具1按钮初始化
    detailPageTool1Init();
    // 详情页顶部栏按钮初始化
    detailPageTopBarInit();
  }
  // 降权旺旺号
  dbgjUploadWw.init();
}
// 详情页工具2
function detailPageTool2Init() {
  $(".dbgj-product-details-tool2 .dbgj-warn-btn").click(function () {
    if (!dbgjObj.isLogin) {
      Message("请先登录", 3, 3000);
      $("#dbgj-home .dbgj-feature-page").addClass("dbgj-hide")
      $("#dbgj-register-login-page").removeClass("dbgj-hide");
      return false;
    }
    let index = $(this).attr("index");
    // 秒变手淘
    if (index == 6) {
      let html = `<div style="width:410px;height:700px;" id="dbgj-toolHandTao-iframe-box">
      <iframe
          style="border:none;"
          width="100%"
          height="100%"
          id="dbgj-toolHandTao-iframe"
          src=""
        ></iframe></div>`;
      Dialog("秒变手淘", html, 435, 768);
      (function () {
        let id = dbgjObj.getCurrentPageId();
        let iframeUrl = dbgjObj.isTmall() ? `https://detail.m.tmall.com/item.htm?id=${id}` : `https://h5.m.taobao.com/awp/core/detail.htm?id=${id}`;
        let iframe = document.getElementById("dbgj-toolHandTao-iframe");
        iframe.setAttribute("src", iframeUrl);
        let iframeBox = document.getElementById("dbgj-toolHandTao-iframe-box");
        if (iframe.attachEvent) { // 兼容IE写法
          iframe.attachEvent("onload", function () {
            // iframe加载完成后要进行的操作
            iframeBox.style.cssText = "width:435px;height:700px;background:#fff;margin: 0 auto;";
          })
        } else {
          iframe.onload = function () {
            // iframe加载完成后要进行的操作
            iframeBox.style.cssText = "width:435px;height:700px;background:#fff;margin: 0 auto;";
          }
        }
      })();
    } else if (index == 4) {
      // SKU分析
      Dialog("详情页工具", dbgjDetailsToolsHtml, 1352, 700)
      chooseFeature(31);
      detailsToolInit(31);
    } else if (index == 5) {
      Dialog("详情页工具", dbgjDetailsToolsHtml, 1352, 700)
      chooseFeature(33);
      detailsToolInit(33);
    } else if (index == 1) {
      // 主图视频下载
      Dialog("主图&视频下载", toolBarVideoDownloadHtml, 800, 350)
      let videoNode = null;
      const video = document.querySelector("video source");
      const video2 = document.querySelector("video");
      if (video || video2) {
        $(".dialog-video-btn-box").find(".download-mainVideo").show();
        video ? (videoNode = video) : (videoNode = video2);
      }
      // 视频下载按钮
      $(".dialog-video-btn-box").on("click", ".download-mainVideo", function() {
        const videoSrc = videoNode.src;
        const title = dbgjObj.getCommodityTitle();
        dbgjObj.loadingOpen();
        dbgjObj.getFileResolve(videoSrc).then(res => {
          dbgjObj.loadingClose();
          dbgjObj.openDownloadDialog(res, `视频-${title}.mp4`);
        }).catch(err => {
          Message("请刷新页面重新尝试下载，该商品视频为加密视频", 2, 4000);
        })
      });
      // 主图下载
      $(".dialog-video-btn-box").on("click", ".download-mainImg", function() {
        dbgjObj.loadingOpen();
        let imgNodeList = document.querySelectorAll("#J_UlThumb img");
        const imgReg = /[\d]{2,3}x[\d]{2,3}/g;
        let imgPostfix = "";
        let imgSrcArr = [];
        for(let i = 0; i < imgNodeList.length; i++) {
          let src = imgNodeList[i].src;
          src = src.replace(imgReg, "800x800");
          src = src.replace(/_.webp/, "");
          imgSrcArr.push(src);
        }
        let resArr = [];
        imgPostfix = imgSrcArr[0].replace(/.+\./, "").toLowerCase();
        for (let j = 0; j < imgSrcArr.length; j++) {
          let item = imgSrcArr[j]
          let res = dbgjObj.getFileResolve(item);
          resArr.push(res);
        }
        //新建压缩
        const jsZip = new JSZip();
        let title = dbgjObj.getCommodityTitle();
        let rarName = "主图"+ title;
        let zip = jsZip.folder(rarName);
          //添加到压缩文件夹
          for(let k = 0; k < resArr.length; k++) {
            let item = resArr[k];
            if (item === "error") {
              //TODO 做什么？？
            } else {
              zip.file(`主图${k}.${imgPostfix}`, item);
            }
          }
          //压缩文件，然后发起下载
          zip.generateAsync({ type: "blob" }).then(content => {
            dbgjObj.loadingClose();
            Message("主图打包成功请下载");
            dbgjObj.openDownloadDialog(content, `${rarName}.zip`);
          });
        });
      
    } else if (index == 3) {
      // 买家秀下载
      let thumbnailsArr = [];
      let zipCode = 10;
      let imageSuffix = []; //图片后缀
      Dialog("买家秀下载", toolBarByuerShowZipHtml, 800, 350);
      let pid = dbgjObj.getCurrentPageId();
      dbgjObj.loadingOpen();
      ajaxFetch("POST", dbgjBase + "/sku/getAllBuyers", {productId: pid}, function (res) {
        dbgjObj.loadingClose();
        thumbnailsArr = res.data.thumbnails;
        let num = res.data.thumbnails.length;
        num = Number(num);
        if (num <= 0) {
          Message("暂无买家秀图片", 3, 3000);
          $(".dialog-buyerShow-btn-box").find(".no-zip-buyshow-img").show();
          $(".dialog-buyerShow-btn-box").find(".zip-buyshow-img").hide();
          return;
        }
        $(".dialog-buyerShow-btn-box").find(".no-zip-buyshow-img").hide();
        if (num > 200) {
          $(".dialog-buyerShow-btn-box").find(".zip-buyshow-img").show();
        }
        if (num > 100 && num < 200) {
          $(".dialog-buyerShow-btn-box").find(".zip-buyshow-img").show();
        }
        if (num > 50 && num < 100) {
          $(".dialog-buyerShow-btn-box").find(".zip-buyshow-img").each(function () {
            if ($(this).attr("data-num") == "200") {
              $(this).hide();
            } else {
              $(this).show();
            }
          });
        }
        if (num <= 50 && num > 0) {
          $(".dialog-buyerShow-btn-box").find(".zip-buyshow-img").each(function (index) {
            if ($(this).attr("data-num") == "200" || $(this).attr("data-num") == "100") {
              $(this).hide();
            } else {
              $(this).show();
            }
          });
        }
      });
      //打包图片
      
      // 打包买家秀图片
      $(".dialog-buyerShow-btn-box .zip-buyshow-img").click(function () {
        let num = $(this).attr("data-num");
        if (thumbnailsArr.length === 0) {
          Message('暂无数据可以下载', 3, 3000);
          return
        }
        if (num === "all") {
          thumbnails = thumbnailsArr
        } else {
          num = Number(num);
          thumbnails = thumbnailsArr.filter((item, index) => {
            return index < num
          });
        }
        thumbnails.reverse();
        if (thumbnails !== '') {
          layer.alert('正在采集中，请稍等...', {
            icon: 1,
            skin: 'layer-ext-moon' //该皮肤由layer.seaning.com友情扩展。关于皮肤的扩展规则，去这里查阅
          });
          let zip = new JSZip
          let img = zip.folder("images")
          thumbnails.forEach((v, i) => {
            let suffix = v.substring(v.lastIndexOf("."))
            imageSuffix.push(suffix)
            //转文件对象
            let arr = dbgjObj.getFileResolve(v)
            img.file('买家秀' + i + imageSuffix[i], arr);
          })
          setTimeout(() => {
            zip.generateAsync({
              //接收文件对象
              type: "blob"
            }).then(function (content) {
              // see FileSaver.js
              Message("采集买家秀完毕");
              saveAs(content, "买家秀.zip");
            });
          }, 100)
        } else {
          MessageBox("买家秀", '打包图片失败');
        }
        //倒计时
        // let packTime = setInterval(() => {
        //   zipCode--;
        //   if (zipCode == 0) {
        //     zipCode = 10
        //     layer.alert('采集买家秀完毕', {
        //       icon: 1,
        //       time: 5000,
        //       skin: 'layer-ext-moon' //该皮肤由layer.seaning.com友情扩展。关于皮肤的扩展规则，去这里查阅
        //     });
        //     clearInterval(packTime);
        //   }
        // }, 1000)
      });
    }
  })
}
// 一键报表
function onekeyStatementInit() {
  dbgjObj.loadingOpen();
  let pid = dbgjObj.getCurrentPageId();
  // 渲染竞品分析的表格数据
  // 竞品分析
  (function (pid) {
    let list_content_product = $("#data_analysis_list_content");
    let list_item_product = $("#data_analysis_list_item");
    let seven_content = $('#data_analysis_seven_content');
    let seven_item = $('#data_analysis_seven_item');
    function findProductPage(params) {
      dbgjObj.loadingOpen();
      list_item_product.remove();
      seven_item.remove();
      ajaxFetch("POST", dbgjBase + '/remoteGainAnalysis/product', params, function (res) {
        if (res.code === "1") return;
        if (res.code === '0') {
          let data = res.data;
          list_content_product.empty();
          seven_content.empty();
          //						表格时间从大到小
          for (let i = 0; i < data.length; i++) {
            // for(var i = data.length - 1; i >= 0; i--) {
            let oneData = data[i];
            let index = i;
            let listItem = list_item_product.clone();
            listItem.css('display', '');
            listItem.attr('id', '');
            listItem.find('.sortNo').text(index + 1);
            listItem.find('.dateStr').text(oneData.dateStr);
            listItem.find('.payRateIndex').text(oneData.payRateIndex + "% ");
            listItem.find('.uvIndex').text(oneData.uvIndex);
            listItem.find('.tradeIndex').css('display', '');
            listItem.find('.tradeIndex').text(oneData.tradeIndex);
            listItem.find('.payByrCntIndex').text(oneData.payByrCntIndex);
            listItem.find('.keda').text(oneData.keda);
            listItem.find('.uvjz').text(oneData.uvjz);
            list_content_product.append(listItem);
          };
          if (params.dateType == 1 || params.dateType == 4) {
            $("#dialog-content-onekeyStatement").find('.seven_table').hide();
          } else {
            $("#dialog-content-onekeyStatement").find('.seven_table').show();
          }
          //表格汇总
          $('.senven_len').text(data.length);
          let sum_uvIndex = 0; //7天总买家 
          let sum_payByrCntIndex = 0; //7天总买家 
          let sum_tradeIndex = 0; // 7天总金额
          let sum_payRateIndex = 0; // 7天平均转化率
          let sum_keda = 0; //7天平均客单价
          let sum_uvjz = 0; // 7天平均UV价值
          data.forEach((item, index) => {
            sum_uvIndex = sum_uvIndex + parseFloat(item.uvIndex.replace(/,/g, ""));
            sum_payByrCntIndex = sum_payByrCntIndex + parseFloat(item.payByrCntIndex.replace(/,/g, ""));
            sum_tradeIndex = sum_tradeIndex + parseFloat(item.tradeIndex.replace(/,/g, ""));
            sum_payRateIndex = sum_payRateIndex + parseFloat(item.payRateIndex.replace(/,/g, ""));
            sum_keda = sum_keda + parseFloat(item.keda.replace(/,/g, ""));
            sum_uvjz = sum_uvjz + parseFloat(item.uvjz.replace(/,/g, ""));

          });
          let sumItem = seven_item.clone();
          sumItem.find('.sum_uvIndex').text(sum_uvIndex);
          sumItem.find('.sum_payByrCntIndex').text(sum_payByrCntIndex);
          sumItem.find('.sum_tradeIndex').text(sum_tradeIndex);
          sumItem.find('.sum_payRateIndex').text(parseFloat(sum_payRateIndex / data.length).toFixed(2) + '%');
          sumItem.find('.sum_keda').text(parseFloat(sum_keda / data.length).toFixed(2));
          sumItem.find('.sum_uvjz').text(parseFloat(sum_uvjz / data.length).toFixed(2));
          sumItem.find('.senven_date').text(data[data.length - 1].dateStr + '至' + data[0].dateStr + '(' + data.length + '天)');
          seven_content.append(sumItem);
        } else {
          list_content_product.empty();
          MessageBox("竞品分析", res.msg);
        }
      });
    }
    // 商品信息请求
    ajaxFetch("POST", dbgjBase + "/product/detail", { productId: pid }, function (res) {
      const {
        code,
        data
      } = res;
      if (code === "1") return;
      $("#dialog-content-onekeyStatement .dbgj-goods-info-img").attr("src", data.item.images[0]);
      $("#dialog-content-onekeyStatement .dbgj-goods-info-title").text(data.item.title);
      $("#dialog-content-onekeyStatement .dbgj-goods-info-shop").text(data.seller.shopName);
      $("#dialog-content-onekeyStatement .dbgj-goods-info-price").text(data.price);
      $("#dialog-content-onekeyStatement .dbgj-goods-info-buyerCount").text(data.sales);
    });
    // 竞品分析请求
    findProductPage({
      productId: pid,
      dateType: "3"
    });
    // 初始化日期选择器
    $('#product-analysis-laydate').datepicker({
      'format': 'yyyy-mm-dd',
      'autoclose': true
    }).on("changeDate", function (e) {
      let selectDate = $("#product-analysis-laydate").val();
      findProductPage({
        productId: pid,
        dateType: 4,
        dateRange: selectDate
      });
    });
    // 切换天数数据类型
    $("#dialog-content-21 .dbgj-date-pick-box .tab-item").click(function () {
      if (!$(this).hasClass("selected")) {
        $(this).addClass("selected").siblings(".tab-item").removeClass("selected");
        let dateType = $(this).attr("data-id");
        findProductPage({
          productId: pid,
          dateType: dateType
        });
      }
    });
    // 竞品分析导出数据
    $("#derive-analysis-excel").click(function () {
      let dateType = $("#dialog-content-21 .dbgj-date-pick-box").find(".tab-item.selected").attr("data-id");
      let selectDate = $("#product-analysis-laydate").val();
      if ($.isEmpty(selectDate)) {
        selectDate = "";
      } else {
        dateType = 4
      }
      let params = {
        productId: pid,
        dateType: dateType,
        dateRange: selectDate
      }
      downloadFile("/analysis/product/getAnalysisExportExcel", params, "竞品分析数据-");
    });
    
  })(pid);

  // SKU占比
  (function(pid) {
    function myChart() {
      // 基于准备好的dom，初始化echarts实例
      var myChart = echarts.init(document.getElementById('skuPieChart'));
      // 指定图表的配置项和数据
      option = {
        tooltip: {
          trigger: 'item',
          formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        series: [{
          name: '访问来源',
          type: 'pie',
          color: ['#1790FF', '#F98F37', '#FED137', '#8196FE', '#46D694', '#F98F37'],
          radius: ['50%', '70%'],
          data: [{
            value: 2.3,
            name: '主要颜色:68深蓝色,尺码:155/80A/S',
          }, {
            value: 5.1,
            name: '主要颜色:09黑色,尺码:155/80A/S',
          }, {
            value: 2.5,
            name: '主要颜色:14玛瑙红色,尺码:160/84A/M'
          }, {
            value: 3.8,
            name: '主要颜色:58深绿色,尺码:155/80A/S'
          }, {
            value: 13.4,
            name: '主要颜色:46鹅黄色,尺码:160/84A/M'
          }, {
            value: 10.8,
            name: '主要颜色:46鹅黄色,尺码:155/80A/S'
          }],
          itemStyle: {
            emphasis: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      };
      if (option && typeof option === "object") {
        myChart.setOption(option, true);
      }
    };
    myChart();
    // sku占比分页
    function pagingSku(params) {
      const {
        productId,
        pageCount,
        startnum
      } = params;
      $('#skuPieChart').css("display", 'none'); //隐藏饼图
      skuListContentObj.empty();
      let skuPageData = skuData.filter((item, index) => {
        const newIndex = index + 1
        const max = startnum * 5 //末端数据
        const min = max - 5 + 1 //首端数据
        if (newIndex >= min && newIndex <= max) {
          return item
        }
      })
      let length = skuPageData.length;
      for (let i = 0; i < length; i++) {
        let oneData = skuPageData[i];
        let listItem = sukListItemObj.clone();
        listItem.find('.dataNum_sku').text(i + 1);
        listItem.find('.auctionNumId_sku').text(productId);
        listItem.find('.type_sku').text(strReplace(oneData.skuName));
        listItem.find('.rate_sku').text(oneData.ratio);
        skuListContentObj.append(listItem);
      }
      $('#skuTable').css("display", ''); //显示列表
      Page({
        num: pageCount, //页码数
        startnum: startnum, //指定页码
        elem: $('#pageSku'), //指定的元素
        callback: function (num) { //回调函数
          pagingSku({
            productId: productId,
            pageCount: pageCount,
            startnum: num
          })
        }
      });
    }
    //sku评价分页
    let feekback = [],
      skuData = [];
    // let listContentObj = $('#skuEvaluate-table-body');
    // let listItemObj = $('#skuEvaluate-table-item');
    let skuListContentObj = $('#list_content_sku');
    let sukListItemObj = $('#list_item_sku');
    // sku信息请求
    function findPage(productId, type) {
      dbgjObj.loadingOpen();
      ajaxFetch("POST", dbgjBase + "/sku/searchComment", {
        productId: productId,
        type: type
      }, function (res) {
        dbgjObj.loadingClose();
        if (res.code === "1") return;
        if (res.code === "0") {
          // if (res.data.feekback.length === 0) {
          //   Message("SKU评价暂无数据", 3, 4000);
          // }

          // feekback = res.data.feekback;
          // let pageCount = parseInt(
          //   Math.ceil(feekback.length / 10)
          // );
          // paging({
          //   pageCount: pageCount,
          //   startnum: 1
          // });
          //sku
          if (res.data.sku.length === 0) {
            Message("SKU占比暂无数据", 3, 4000);
            return;
          }
          let skuArray = [];
          skuData = res.data.sku;
          let length = skuData.length;
          if (length <= 20) {
            $('#skuPieChart').css("display", ''); //显示饼图
            $('#skuTable').css("display", 'none'); //隐藏列表
            for (let i = 0; i < length; i++) {
              let one = skuData[i];
              let value = one.ratio;
              value = value.replace('%', '');
              let key = one.skuName;
              key = strReplace(key);
              let skuArrayItem = {
                value: value,
                name: key
              };
              skuArray[i] = skuArrayItem;
            }
            let myChart = echarts.init(document.getElementById('skuPieChart'));
            myChart.setOption({
              series: [{
                data: skuArray
              }]
            });
          } else {
            let pageCount = parseInt(
              Math.ceil(length / 5)
            );
            pagingSku({
              productId: productId,
              pageCount: pageCount,
              startnum: 1
            })
          }
        }
      });
    }
    // SKU占比评价分析
    findPage(pid, "1");
    // 导出sku占比数据
    $("#derive-skuRatioData-excel").click(function () {
      if (skuData.length <= 0) {
        Message("请先获取到数据再导出", 3, 3000);
        return;
      }
      downloadFile("/skuResearch/getExportExcel", {
        productId: pid,
        sku: skuData
      }, "sku占比数据");
    });
  })(pid);

  // 采集问大家
  (function(pid) {
    let questionWords = [],
      questionFeeds = [],
      questionWordsType = "全部";
    let questionListContentObj = $("#question_list_content");
    // let questionListItemObj = $("#question_list_item");
    // 问大家分页
    function askQuestionPage(type, pageNumber) {
      if (questionWordsType !== type) {
        pageNumber = 1
      }
      questionListContentObj.empty();
      // 筛选相同的问题
      let QuestionFeeds = [];
      if (type === "全部") {
        QuestionFeeds = questionFeeds;
      } else {
        QuestionFeeds = questionFeeds.filter((item) => {
          if (item.title.indexOf(type) !== -1) {
            return item;
          }
        });
      }

      // 分页
      let fiterQuestionFeeds = QuestionFeeds.filter((item, index) => {
        const newIndex = index + 1
        const max = pageNumber * 5 //末端数据
        const min = max - 5 + 1 //首端数据
        if (newIndex >= min && newIndex <= max) {
          return item
        }
      })
      let pageCount = parseInt(
        Math.ceil(QuestionFeeds.length / 5)
      );
      for (let i = 0; i < fiterQuestionFeeds.length; i++) {
        let oneData = fiterQuestionFeeds[i];
        let subFeeds = oneData.subFeeds.filter((item, index) => {
          return index < 3
        });
        let title = oneData.title;
        let gmtCreate = dbgjObj.timestampToDate(oneData.gmtCreate, "onlyDate");
        for (let j = 0; j < subFeeds.length; j++) {
          let twoData = subFeeds[j];
          if (twoData.userScore === null) {
            twoData.userScore = ""
          }
          if (subFeeds.length > 1) {
            if (j === 0) {
              let questionListItemHtml = `
              <tr id="question_list_item">
                <td rowspan=${subFeeds.length} class="gmtCreate">${gmtCreate}</td>
                <td rowspan=${subFeeds.length} class="title">${title}</td>
                <td class="subTitle">${twoData.title}</td>
                <td class="subGmtCreate">${dbgjObj.timestampToDate(twoData.gmtCreate, "onlyDate")}</td>
                <td class="subUserNick">${dbgjObj.userNickFilter(twoData.userNick)}</td>
                <td class="subUserScore" style="display:none">${twoData.userScore}</td>
              </tr>`
              questionListContentObj.append(questionListItemHtml);
            } else {
              let questionListItemHtml = `
              <tr id="question_list_item">
                <td rowspan=${subFeeds.length} class="gmtCreate" style="display:none">${gmtCreate}</td>
                <td rowspan=${subFeeds.length} class="title" style="display:none">${title}</td>
                <td class="subTitle">${twoData.title}</td>
                <td class="subGmtCreate">${dbgjObj.timestampToDate(twoData.gmtCreate, "onlyDate")}</td>
                <td class="subUserNick">${dbgjObj.userNickFilter(twoData.userNick)}</td>
                <td class="subUserScore" style="display:none">${twoData.userScore}</td>
              </tr>`
              questionListContentObj.append(questionListItemHtml);
            }
          } else {
            let questionListItemHtml = `
              <tr id="question_list_item">
                <td class="gmtCreate">${gmtCreate}</td>
                <td class="title">${title}</td>
                <td class="subTitle">${twoData.title}</td>
                <td class="subGmtCreate">${dbgjObj.timestampToDate(twoData.gmtCreate, "onlyDate")}</td>
                <td class="subUserNick">${dbgjObj.userNickFilter(twoData.userNick)}</td>
                <td class="subUserScore" style="display:none">${twoData.userScore}</td>
              </tr>`
            questionListContentObj.append(questionListItemHtml);
          }
        }
      }
      Page({
        num: pageCount, //页码数
        startnum: pageNumber, //指定页码
        elem: $('#askQuestion-page'), //指定的元素
        callback: function (num) { //回调函数
          askQuestionPage(type, num);
        }
      });
    }
    // 采集问大家搜索
    // 问大家请求
    dbgjObj.loadingOpen();
    ajaxFetch("POST", dbgjBase + "/product/questionnaire", { productId: pid }, function (res) {
      const {
        code,
        data
      } = res;
      if (code === "1") return;
      if (data.questionWords.length === 0 && data.feeds.length === 0) {
        Message("暂无数据", 3, 3000);
        $("#questionWords_type_list").empty();
        return;
      }
      questionWords = ["全部", ...data.questionWords];
      questionWordsType = "全部";
      $("#questionWords_type_list").empty();
      for (let i = 0; i < questionWords.length; i++) {
        let name = questionWords[i];
        if (name === "全部") {
          $("#questionWords_type_list").append(`<span class="dbgj-primary-btn dbgj-mr-10 dbgj-mb-10 active">${name}</span>`);
        } else {
          $("#questionWords_type_list").append(`<span class="dbgj-primary-btn dbgj-mr-10 dbgj-mb-10">${name}</span>`);
        }
      }
      // 过滤掉空的问题
      questionFeeds = data.feeds.filter(item => {
        if (item.title) {
          return item
        }
      });
      askQuestionPage("全部", 1);
    });
    // 绑定问大家关键词
    $("#questionWords_type_list").on("click", ".dbgj-primary-btn", function () {
      $(this).addClass("active").siblings(".dbgj-primary-btn").removeClass("active");
      let text = $(this).text();
      questionWordsType = text;
      askQuestionPage(text, 1);
    });
    // 导出问大家的数据
    $("#derive-ask-excel").click(function () {
      downloadFile("/product/questionnaire/getExportExcel", {
        productId: pid
      }, "采集问大家数据-");
    });
  })(pid);
}
// 详情页工具1
function detailPageTool1Init() {
  
  //  自动获取淘客信息
  (function() {
    if (!dbgjObj.isLogin) {
      Message("请先登录", 3, 3000);
      $("#dbgj-home .dbgj-feature-page").addClass("dbgj-hide")
      $("#dbgj-register-login-page").removeClass("dbgj-hide");
      return false;
    }
    let itemId = dbgjObj.getCurrentPageId();
    $.ajax({
      type: "POST",
      url: dbgjBase + "/tbk",
      data: JSON.stringify({itemId: itemId}),
      dataType: 'json',
      contentType: "application/json;charset=UTF-8",
      headers: {
        "token": localStorage.getItem("dbgjToken") ? localStorage.getItem("dbgjToken") : "",
      },
      success: function (res) {
        const {
          code,
          msg
        } = res;
        if (code === "201" || code === "202") {
          dbgjObj.isLogin = false;
          Message(msg, 3, 3000);
          layer.closeAll();
          $("#dbgj-home .dbgj-feature-page").addClass("dbgj-hide")
          $("#dbgj-register-login-page").removeClass("dbgj-hide");
          $("#dbgj-register-login-page .dbgj-login-code-box .refresh-code").removeClass("dbgj-hide").siblings(".scan-code").addClass("dbgj-hide");
          return false;
        } else if (code === "1") {
         
        }
        if (res.code == 0) {
          let data = res.data;
          let taokeHtml = `
          <div class="tk_box">
            <span>佣金:</span><span class="dbgj-font-red">￥${data.tkCommissionAmount}</span>
          </div>
          <div class="tk_box">
            <span>月支出:</span><span class="dbgj-font-red">￥${data.totalFee}</span>
          </div>
          <div class="tk_box">
            <span>月推广:</span><span class="dbgj-font-red">${data.tkTotalSales}件</span>
          </div>
          <div class="tk_box">
            <span>最高比率:</span><span class="dbgj-font-red">${data.tkCommonRate}%</span>
          </div>
          <div class="tk_box">
            <span>比率:</span><span class="dbgj-font-red">${data.calTkRate}</span>
          </div>
          <div class="tk_box">
            <span>优惠券金额:</span><span class="dbgj-font-red">￥${data.couponPrice}</span>
          </div>
          <div class="tk_box">
            <span>发放优惠券:</span><span class="dbgj-font-red">${data.couponSendCount}</span>
          </div>
          <div class="tk_box">
            <span>剩余优惠券:</span><span class="dbgj-font-red">${data.couponRemainCount}</span>
          </div>
          <div class="tk_box">
            <span>在售价:</span><span class="dbgj-font-red">￥${data.price}</span>
          </div>
          <div class="tk_box">
            <span>券后价:</span><span class="dbgj-font-red">￥${data.priceAfterCoupon}</span>
          </div>`;
          $(".dbgj-product-details-tool1").find(".has_tk").html(taokeHtml);
          $(".dbgj-product-details-tool1").find(".no_tk").addClass('dbgj-hide');
          $(".dbgj-product-details-tool1").find(".has_tk").removeClass('dbgj-hide');
        } else {
          $(".dbgj-product-details-tool1").find(".no_tk").removeClass('dbgj-hide');
          $(".dbgj-product-details-tool1").find(".has_tk").addClass('dbgj-hide');
        }
      },
      eror: function (err) {
        console.log(err);
      }
    })
  })();
  
}
// 顶部栏
function detailPageTopBarInit() {
  if (!dbgjObj.isLogin) {
    $("#dbgj-home .dbgj-feature-page").addClass("dbgj-hide")
    $("#dbgj-register-login-page").removeClass("dbgj-hide");
    return false;
  }
  let pid = dbgjObj.getCurrentPageId();
  // // 30天的
  // ajaxFetch("POST", dbgjBase + '/remoteGainAnalysis/product', {dateType: "3", productId: pid}, function (res) {
  //   dbgjObj.loadingClose();
  //   if (res.code === "1") return;
  //   if (res.code === '0') {
  //     let data = res.data;
  //     //表格汇总
  //     let sum_uvIndex = 0; //7天总买家 
  //     let sum_payByrCntIndex = 0; //7天总买家
  //     let sum_tradeIndex = 0; // 7天总金额
  //     let sum_payRateIndex = 0; // 7天平均转化率
  //     let sum_keda = 0; //7天平均客单价
  //     let sum_uvjz = 0; // 7天平均UV价值
  //     for(let i in data) {
  //       let item = data[i];
  //       sum_uvIndex = sum_uvIndex + parseFloat(item.uvIndex.replace(/,/g, ""));
  //       sum_payByrCntIndex = sum_payByrCntIndex + parseFloat(item.payByrCntIndex.replace(/,/g, ""));
  //       sum_tradeIndex = sum_tradeIndex + parseFloat(item.tradeIndex.replace(/,/g, ""));
  //       sum_payRateIndex = sum_payRateIndex + parseFloat(item.payRateIndex.replace(/,/g, ""));
  //       sum_keda = sum_keda + parseFloat(item.keda.replace(/,/g, ""));
  //       sum_uvjz = sum_uvjz + parseFloat(item.uvjz.replace(/,/g, ""));
  //     }
  //     let sumItem = $("#topBarSumItem");
  //     // sumItem.find('.sum_uvIndex').text(sum_uvIndex);
  //     sumItem.find('.payByrCntIndex').text(sum_payByrCntIndex);
  //     sumItem.find('.tradeIndex').text(sum_tradeIndex);
  //     sumItem.find('.payRateIndex').text(parseFloat(sum_payRateIndex / data.length).toFixed(2) + '%');
  //     sumItem.find('.keda').text(parseFloat(sum_keda / data.length).toFixed(2));
  //     sumItem.find('.uvjz').text(parseFloat(sum_uvjz / data.length).toFixed(2));
  //   } else {
  //     MessageBox("竞品分析", res.msg);
  //   }
  // });
  // // 获取昨天销量
  // let date = new Date(); //实例一个时间对象；
  // let year = date.getFullYear(); //获取系统的年；
  // let month = date.getMonth() + 1; //获取系统月份，由于月份是从0开始计算，所以要加1
  // let day = date.getDate() - 1; // 获取昨日
  // if (month < 10) {
  //   month = "0" + month;
  // }
  // if (day < 10) {
  //   day = "0" + day
  // }
  // let yesterday = year + "-" + month + "-" + day;
  // ajaxFetch("POST", dbgjBase + '/remoteGainAnalysis/product', {dateType: "4", dateRange: yesterday, productId: pid}, function (res) {
  //   if (res.code === "1") return;
  //   if (res.code === '0') {
  //     let data = res.data;
  //     let y_payByrCntIndex = parseFloat(data[0].payByrCntIndex.replace(/,/g, ""));
  //     $("#topBarSumItem").find(".y_payByrCntIndex").text(y_payByrCntIndex);
  //   }
  // });

  // 获取下架时间
  let putawayTimestamp = dbgjObj.analysisPutawayTimestamp();
  let type = dbgjObj.isTmall() ? "1" : "2";
  ajaxFetch("POST", dbgjBase + "/product/removalTime", {timestamp: putawayTimestamp, type: type}, function(res) {
    if (res.code === "1") return;
    let timeText = dbgjObj.getDateAndWeek(res.data);
    $(".dbgj-product-details-bar").find(".removalTime").text(timeText);
  });
  // 获取商品类目
  ajaxFetch("POST", dbgjBase + "/product/categoryAll", { productId: pid }, function(res) {
    if (res.code === "1") return;
    $(".dbgj-product-details-bar").find(".categoryType").text(res.data.name);
    $("#categoryTypeTips").attr("data-tips", res.data.path);
  });
}

// 后台订单列表初始化
function sellerBgOrderListInit() {
  if (!dbgjObj.isLogin) {
    // Message("请先登录", 3, 3000);
    $("#dbgj-home .dbgj-feature-page").addClass("dbgj-hide")
    $("#dbgj-register-login-page").removeClass("dbgj-hide");
  }
  const tradeBindingNodeList = document.querySelectorAll(
    '.row-mod__row___sz0Gl[data-reactid=".0.6.0"]'
  );
  if (tradeBindingNodeList > 1) {
    //TODO 报告后台
    return;
  }
  //挂载到页面上
  
  const node = tradeBindingNodeList[0];
  const div = document.createElement("div");
  div.innerHTML = dbgjSellerBgAllOrderHtml;
  node.appendChild(div);
  //检查页面上 订单列表
  const nodeList = document.querySelectorAll(
    ".table-mod__table___3sqJL.item-mod__head___38O6X .item-mod__thead-cell___3aIQ_[colspan]"
  );
  //挂载到订单列表node上
  nodeList.forEach((item, index) => {
    let icNode = item.childNodes;
    let cNode = null;
    let orderId = '', wangwang="";
    for (let i = 0; i < icNode.length; i++) {
      if (icNode[i].getAttribute("class").indexOf("item-mod__checkbox-label___cRGUj") >= 0 ) {
        cNode = icNode[i];
        let idNode = cNode.parentNode.parentNode.parentNode.parentNode.parentNode.querySelector(".table-mod__table___3sqJL.suborder-mod__order-table___2SEhF");
        const a = idNode.querySelector(
          ".sol-mod__no-br___dK-US a"
        );
        const snapshootLink = a.href;
        const reg = new RegExp("[?trade]ID=([^&]+)");
        const query = snapshootLink.match(reg);
        orderId = query ? query[1] : null;
        const ww = cNode.parentNode.parentNode.parentNode.parentNode.parentNode.querySelector(
          ".buyer-mod__name___S9vit"
        );
        wangwang = ww.innerText;
      }
    }
    const span = document.createElement("span");
    span.className = "dbgjSellerBox";
    span.setAttribute("data-order", orderId);
    span.setAttribute("data-wangwang", wangwang);
    span.innerHTML = dbgjSellerBgOrderHtml;
    if (cNode) {
      item.insertBefore(span, cNode.nextElementSibling);
    } else {
      item.appendChild(span);
    }
  });

  //开启观察者
  let observer = new MutationObserver((nodeList, ob) => {
    nodeList.forEach((item, index) => {
      if (index >= 15) {
        // item.addedNodes[0] 新增的DOM对象
        const node = item.addedNodes[0].querySelector(
          ".table-mod__table___3sqJL.item-mod__head___38O6X .item-mod__thead-cell___3aIQ_[colspan]"
        );
        let oicNode = node.childNodes;
        let ocNode = null;
        let orderId = '';
        let wangwang = '';
        for (let j = 0; j < oicNode.length; j++) {
          if (oicNode[j].getAttribute("class").indexOf("item-mod__checkbox-label___cRGUj") >= 0) {
            ocNode = oicNode[j];
            let idNode = ocNode.parentNode.parentNode.parentNode.parentNode.parentNode.querySelector(".table-mod__table___3sqJL.suborder-mod__order-table___2SEhF");
            const a = idNode.querySelector(
              ".sol-mod__no-br___dK-US a"
            );
            const snapshootLink = a.href;
            const reg = new RegExp("[?trade]ID=([^&]+)");
            const query = snapshootLink.match(reg);
            orderId = query ? query[1] : null;
            const ww = ocNode.parentNode.parentNode.parentNode.parentNode.parentNode.querySelector(
              ".buyer-mod__name___S9vit"
            );
            wangwang = ww.innerText;
          }
        }
        const ospan = document.createElement("span");
        ospan.className = "dbgjSellerBox";
        ospan.setAttribute("data-order", orderId);
        ospan.setAttribute("data-wangwang", wangwang);
        ospan.innerHTML = dbgjSellerBgOrderHtml;
        if (ocNode) {
          node.insertBefore(ospan, ocNode.nextElementSibling);
        } else {
          node.appendChild(ospan);
        }
      }
    });
  });
  let gcNode = document.querySelector('[data-reactid=".0.6"]');

  let options = {
    childList: true,
    attributes: true
  };
  observer.observe(gcNode, options);
}
var dbgjUploadWw = {
  shopName: "", // 店铺名
  pageCount: 0, // 违规编号有多少页
  punishArr: [], // 所有的违规订单数组
  isGetOrderWw: true, // 没异常的时候正常获取旺旺
  violationNumReq: {
    // 违规编号（虚假交易）的接口
    url:
      "https://healthcenter.taobao.com/home/json/GetPunishHistory.json?_x=1",
    params: {
      page: 1,
      pageSize: 10,
      startTime: "",
      endTime: "",
      pointRange: "1"
    }
  },
  violationOrderReq: {
    // 获取违规编号下的所有订单的接口链接
    url:
      "https://healthcenter.taobao.com/home/json/get_affect_order_list.do?_x=1"
  },
  getJsonp(url, params) {
   return $.ajax({
      type: "GET",
      url: url,
      data: params,
      dataType: 'jsonp',
      contentType: "application/json;charset=UTF-8"
    })
  },
  fetchData: function*(url, params) {
    yield this.getJsonp(url, params);
  },
  // 违规编号有多少页和总数
  fetchViolationNumPolling() {
    let promise = this.fetchData(
      this.violationNumReq.url,
      this.violationNumReq.params
    ).next().value;
    promise.then(res => {
      const data = res.punish_history_list;
      const { module, pageDO } = data;
      if (pageDO.totalCount !== 0) {
        this.pageCount = parseInt(
          Math.ceil(pageDO.totalCount / pageDO.pageSize)
        );
        // 只能一页一页请求
        this.fetAllviolationNums(1, pageDO.pageSize);
      } else {
        // 有时候请求接口会返回totalCount为0
        setTimeout(() => {
          this.fetchViolationNumPolling();
        }, 2000);
      }
    });
  },
  //获取违规编号下的违规订单
  fetAllviolationNums(page, pageSize) {
    const self = this;
    let temp = {
      page: page,
      pageSize: pageSize,
      startTime: "",
      endTime: "",
      pointRange: ""
    };
    let promiseFirst = self.fetchData(self.violationNumReq.url, temp).next().value;
    promiseFirst.then(result => {
      const punishData = result.punish_history_list;
      const { module, pageDO } = punishData;
      if (module.length !== 0) {
        module.forEach(item => {
          if (item.ruleTypeStr && item.ruleTypeStr === "虚假交易") {
            let obj = {
              violationTime: item.gmtStart,
              dispositionMode: item.handleDetail,
              punishId: item.punishId,
              pageCount: 1
            };
            self.punishArr.push(obj);
          }
        });
        if (page < self.pageCount) {
          self.fetAllviolationNums(page + 1, pageSize);
          return false;
        } else if (self.punishArr.length !== 0 && self.pageCount === page) {
          // 到最后一页页数再请求获取下面的违规订单
          // self.fetchViolationOrder(self.punishArr[0]);
          self.toLookOrders(self.punishArr[0]);
        }
      }
    }).catch(err => {
      setTimeout(() => {
        self.fetAllviolationNums(page, pageSize);
      }, self.randomNum(300, 500));
    });
  },
  randomNum(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  },
  // 模拟点击去查看订单无论失败还是成功都是获取违规订单了
  toLookOrders(punishObj) {
    const tloUrl = `https://healthcenter.taobao.com/home/json/get_fast_modify_info.do`;
    let params = { healthId: "", punishId: punishObj.punishId, fromType: 2 };
    let tloPromise = this.fetchData(tloUrl, params).next().value;
    tloPromise.then(res => {
      this.fetchViolationOrder(punishObj);
    }).catch(err => {
      this.fetchViolationOrder(punishObj);
    });
  },
  // 通过违规编号获取第一页违规订单
  fetchViolationOrder(obj) {
    let params = {
      pageSize: 14,
      page: 1,
      punishId: obj.punishId,
      type: 3
    };
    let gpoPromise = this.fetchData(this.violationOrderReq.url, params).next().value;
    gpoPromise
      .then(result => {
        const { data, page } = result.module;
        let punishIdIndex = this.punishArr.findIndex((value, index, arr) => {
          return value.punishId === obj.punishId;
        });
        let pCount = 1;
        if (page.totalCount > page.pageSize) {
          pCount = parseInt(Math.ceil(page.totalCount / page.pageSize));
        }
        this.punishArr[punishIdIndex].pageCount = pCount;
        // 第一页获取到就直接judgeIsRepeatOrder()
        let onePageDropRight = [];
        if (data.length === 0 || !data.length) {
          return false;
        }
        for(let j = 0; j < data.length; j++) {
          let temp = { "orderNumber": data[j].orderId, "editUrl": `https:${data[j].editUrl}` };
          onePageDropRight.push(temp);
        }
        const { dispositionMode, punishId, violationTime } = obj;
        let oneObj = {dispositionMode, punishId, violationTime, pageCount: 1};
        this.judgeIsRepeatOrder(oneObj, onePageDropRight);
        if (pCount === 1) return false;
        // 获取到总页数 > 2之后一页一页获取违规订单
        for (let i = 2; i <= pCount; i++) {
          (function(i) {
            let param = {
              pageSize: 14,
              page: i,
              punishId: obj.punishId,
              type: 3
            };
            const { dispositionMode, punishId, violationTime } = obj;
            let sobj = {
              dispositionMode: dispositionMode,
              punishId: punishId,
              violationTime: violationTime,
              pageCount: i
            };
            let sendObj = { obj: sobj, params: param };
            setTimeout(function(i) {
              window.postMessage(
                {
                  action: "getPunishOrders",
                  value: sendObj
                },
                "*"
              );
            }, (i - 1) * 3000);
          })(i);
        }
      })
      .catch(err => {
        setTimeout(() => {
          this.fetchViolationOrder(obj);
        }, this.randomNum(300, 500));
      });
  },
  // 请求接口获取没有上传过的订单
  judgeIsRepeatOrder(punishObj, dropRightInfosArr) {
    const { violationTime, dispositionMode, punishId, pageCount } = punishObj;
    let punishIdIndex = this.punishArr.findIndex((value, index, arr) => {
      return value.punishId === punishId;
    });
    let uploadArr = [];
    dropRightInfosArr.forEach(item => {
      uploadArr.push(item.orderNumber);
    });
    let uploadObj = { dropRightNumber: String(punishId), orders: uploadArr };
    let pObj = {violationTime, dispositionMode, punishId, pageCount, punishIdIndex, dropRightInfosArr};
    let sendObj = { uploadObj, punishObj: pObj };
    window.postMessage(
      {
        action: "getDropRightOrderStatus",
        value: sendObj
      },
      "*"
    );
  },
  // 获取到后台去重后的订单数据去获取旺旺
  getRightDownWwOrders(res, punishObj) {
    const { violationTime, dispositionMode, punishId, pageCount, punishIdIndex, dropRightInfosArr} = punishObj;
    const { code, data } = res;
    // 有需要获取旺旺的订单号就去获取
    if (code === "0" && data.length !== 0) {
      let dropRightInfos = [];
      data.forEach(orderId => {
        dropRightInfosArr.forEach(element => {
          if (orderId === element.orderNumber) {
            dropRightInfos.push(element);
          }
        });
      });
      let obj = {
        dropRightNumber: punishId,
        shopName: this.shopName,
        violationTime: violationTime,
        dispositionMode: dispositionMode,
        dropRightInfos: dropRightInfos
      };
      // 去详情页获取旺旺号
      if (!this.isGetOrderWw) return false;
      this.fetchViolationOrderWw(obj);
    }
    
    if (punishIdIndex === this.punishArr.length - 1 && pageCount === this.punishArr[punishIdIndex].pageCount) {
      return false;
    } else if (pageCount === this.punishArr[punishIdIndex].pageCount) {
      // 循环到该punishId最后一页的时候就获取下一个punishId
      setTimeout(() => {
        this.toLookOrders(this.punishArr[punishIdIndex + 1]);
      }, this.randomNum(3000, 5000));
    }
  },
  // 获取旺旺号
  fetchViolationOrderWw(sendObj) {
    // 具体处理在content.js background.js里面
    //需要传以下格式对象
    //    {
    //   dropRightNumber: 123456789,
    //   shopName: "低吟浅唱旗舰店",
    //   violationTime: violationTime,
    //   dispositionMode: dispositionMode,
    //   dropRightInfos: [
    //     {
    //       orderNumber: "657676481506077858",
    //       editUrl: "https://trade.taobao.com/trade/detail/trade_item_detail.htm?bizOrderId=657676481506077858",
    //     },
    //     {
    //       orderNumber: "666064867599383233",
    //       editUrl: "https://trade.taobao.com/trade/detail/trade_item_detail.htm?bizOrderId=666064867599383233",
    //     }
    //   ]
    // }
    // 解决跨域
    setTimeout(() => {
      window.postMessage(
        {
          action: "getDownRightWw",
          value: sendObj
        },
        "*"
      );
    }, this.randomNum(100, 300));
  },
  // 获取店铺名称
  fetchShopName() {
    //获取店铺名
    let shopName = "";
    if (document.querySelector(".sn-user-nick")) {
      shopName = document.querySelector(".sn-user-nick").innerHTML;
    } else {
      shopName = document.querySelector(".user-nick").innerHTML;
    }
    if (shopName) {
      shopName = shopName.split(":")[0];
      this.shopName = shopName;
      // 获取到店铺名就去获取当前浏览器打开了能匹配到的几个标签页
      window.postMessage({
        action: "getRDWwTabsCount",
        value: "getRDWwTabsCount"
      }, '*');
    }
  },
  // 检测当前网址后缀
  check_domain(dbgj_load_href) {
    let dbgj_href = dbgj_load_href ? dbgj_load_href : window.location.href;
    if (
      dbgj_href.indexOf("://healthcenter.taobao.com") >= 0 ||
      dbgj_href.indexOf("://mai.taobao.com/seller_admin.htm") >= 0 ||
      dbgj_href.indexOf("://myseller.taobao.com/home.htm") >= 0
    ) {
      return true;
    }
  },
  callback(e) {
    if (e.data.action === "getStopGetOrderWw" && e.data.value === "stop") {
      // 接口异常了停止获取旺旺
      if (dbgjUploadWw.isGetOrderWw) {
        dbgjUploadWw.isGetOrderWw = false;
      }
      return false;
    } else if (e.data.action === "getPunishOrdersCb") {
      const { obj: punishObj, dropRightArr } = e.data.value;
      dbgjUploadWw.judgeIsRepeatOrder(punishObj, dropRightArr);
    } else if (e.data.action === "getDropRightOrderStatusCb") {
      let { data: result, orginData } = e.data.value;
      result = JSON.parse(result);
      dbgjUploadWw.getRightDownWwOrders(result, orginData);
    } else if (e.data.action === "getRDWwTabsCountCb") {
      if (Number(e.data.value) === 1) {
        // 只有打开第一个匹配到网址的标签页才触发获取违规编号
        dbgjUploadWw.fetchViolationNumPolling();
      }
    }
  },
  init() {
    const self = this;
    window.addEventListener("message", self.callback);
    if (self.check_domain()) {
      // 匹配到三个网址其中一个就触发获取店铺名
      self.fetchShopName();
    }
  }
}

//sycm指数转换
function sycm() {

}
function replace(str) {
  var reg = new RegExp(",", "g"); //g,表示全部替换。
  var replace = str.replace(reg, "");
  return replace;
}
function strReplace(str) {
  var replace2 = str.replace('{', '');
  var sku = replace2.replace('}', '');
  sku = sku.replace(/"/g, '');
  return sku;
}

// 获取二维码重新登录
function getLoginQrCode() {
  dbgjObj.loadingClose();
  dbgjObj.uuid = dbgjObj.getUuid();
  if (dbgjObj.loginTimerId !== null) {
    clearTimeout(dbgjObj.loginTimerId);
  }
  ajaxFetch("GET", dbgjBase + "/qrcode/generateQrcode?scene_str=" + dbgjObj.uuid, null, function (result) {
    getLoginToken(0);
    const {
      code,
      data
    } = result;
    if (code === "0" && data.ticket) {
      let qrCodeUrl = `https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=${data.ticket}`;
      $("#dbgj-register-login-page .dbgj-login-code-box .scan-code").attr("src", qrCodeUrl).removeClass("dbgj-hide").siblings(".refresh-code").addClass("dbgj-hide");
    } else {
      $("#dbgj-register-login-page .dbgj-login-code-box .refresh-code").removeClass("dbgj-hide").siblings(".scan-code").addClass("dbgj-hide");
    }
  });
};
// 生成二维码后轮询获取登录token
function getLoginToken(time) {
  ajaxFetch("GET", dbgjBase + "/user/wxlogin?scene_str=" + dbgjObj.uuid, null, function (result) {
    const {
      code,
      msg,
      bizStatus,
      data
    } = result;
    if (time < 30 && data === null) {
      dbgjObj.loginTimerId = setTimeout(() => {
        time++;
        getLoginToken(time);
      }, 2000);
    }
    if (time >= 30 && time < 60 && bizStatus === "5") {
      Message("二维码已失效，请重新获取！", 3, 2000);
      $("#dbgj-register-login-page .dbgj-login-code-box .refresh-code").removeClass("dbgj-hide").siblings(".scan-code").addClass("dbgj-hide");
      clearTimeout(dbgjObj.loginTimerId);
    }
    if (bizStatus === "6") {
      Message(msg, 3, 2000);
      clearTimeout(dbgjObj.loginTimerId);
      $("#dbgj-bind-phone-page").removeClass("dbgj-hide").siblings("#dbgj-register-login-page").addClass("dbgj-hide");
      dbgjObj.isSendCode = false;
    }
    if (code === "0" && data !== null) {
      //设置到bg
      window.postMessage({
        action: "setToken",
        value: data.token
      }, '*');
      //设置到local
      localStorage.setItem('dbgjToken', data.token);
      clearTimeout(dbgjObj.loginTimerId);
      dbgjObj.isLogin = true;
      Message("登录成功");
      $("#dbgj-register-login-page").addClass("dbgj-hide");
      loginAfterInit();
    }
  });
}
// 获取当前用户相关信息
function getCurrentUserInfo(callback) {
  ajaxFetch("POST", dbgjBase + "/user/getCurrentUser", null, function (res) {
    const {
      data,
      code,
      msg
    } = res;
    if (code === "1") {
      Message(msg, 3, 3000);
      return;
    }
    if (!data) {
      Message("账号信息异常，请重新登录！", 3, 3000);
      dbgjObj.isLogin = false;
      $("#dbgj-home .dbgj-feature-page").addClass("dbgj-hide")
      $("#dbgj-register-login-page").removeClass("dbgj-hide");
      getLoginQrCode();
    } else {
      dbgjObj.currentUserInfo = data;
      $("#dbgj-myCentre-page").find(".avatarUrl").attr("src", data.avatarUrl);
      $("#dbgj-myCentre-page").find(".userName").text(data.userName);
      $("#dbgj-myCentre-page").find(".checkCount").text(data.checkCount);
      $("#dbgj-myCentre-page").find(".taokeCount").text(data.taokeCount);
      $("#dbgj-myCentre-page").find(".tagCount").text(data.tagCount);
      $("#dbgj-myCentre-page").find(".analysisCount").text(data.analysisCount);
      $("#dbgj-myCentre-page").find(".keywordCount").text(data.keywordCount);
      $("#dbgj-myCentre-page").find(".cheaterCount").text(data.cheaterCount);
      $("#dbgj-myCentre-page").find(".goldCoin").text(data.goldCoin);
      let entrancesourceCount = data.entrancesourceCount ? data.entrancesourceCount : "0"
      $("#dbgj-myCentre-page").find(".entrancesourceCount").text(entrancesourceCount);
      let endTime = data.endTime ? dbgjObj.timestampToDate(data.endTime) : "无"
      $("#dbgj-myCentre-page").find(".endTime").text(endTime);
      let vipLevel = data.vipLevel == "0" ? "游客" : data.vipLevel == "1" ? "基础版" : data.vipLevel == "2" ? "豪华版" : data.vipLevel == "3" ? "尊贵版" : "游客";
      $("#dbgj-myCentre-page").find(".vipLevel").text(vipLevel);
      callback && callback();
    }
  });
}

// 插入loading
function injectLoading() {
  $("body").append(loadingHtml);
  $("body").on("click", ".dbgj-loader-bg", function () {
    $(this).hide();
  });

}
// 引入无痕验证
function injectNonTraceValidate() {
  window.NVC_Opt = {
    //无痕配置 && 滑动验证、刮刮卡、问答验证码通用配置
    appkey: 'FFFF0N00000000008322',
    scene: 'nvc_register',
    isH5: false,
    popUp: false,
    renderTo: '#dbgj-fds',
    nvcCallback: function (data) {
      // data为getNVCVal()的值，此函数为二次验证滑动或者刮刮卡通过后的回调函数
      // data跟业务请求一起上传，由后端请求AnalyzeNvc接口，接口会返回100或者900
      // yourRegisterRequest(data);
      getAliCode(dbgjObj.aliPhone);
    },
    trans: {
      "key1": "code0",
      "nvcCode": 400
    },
    language: "cn",
    //滑动验证长度配置
    customWidth: 300,
    //刮刮卡配置项
    width: 300,
    height: 100,
    elements: [
      '//img.alicdn.com/tfs/TB17cwllsLJ8KJjy0FnXXcFDpXa-50-74.png',
      '//img.alicdn.com/tfs/TB17cwllsLJ8KJjy0FnXXcFDpXa-50-74.png'
    ],
    bg_back_prepared: '//img.alicdn.com/tps/TB1skE5SFXXXXb3XXXXXXXXXXXX-100-80.png',
    bg_front: '',
    obj_ok: '//img.alicdn.com/tfs/TB1rmyTltfJ8KJjy0FeXXXKEXXa-50-74.png',
    bg_back_pass: '//img.alicdn.com/tfs/TB1KDxCSVXXXXasXFXXXXXXXXXX-100-80.png',
    obj_error: '//img.alicdn.com/tfs/TB1q9yTltfJ8KJjy0FeXXXKEXXa-50-74.png',
    bg_back_fail: '//img.alicdn.com/tfs/TB1w2oOSFXXXXb4XpXXXXXXXXXX-100-80.png',
    upLang: {
      "cn": {
        _ggk_guide: "请摁住鼠标左键，刮出两面盾牌",
        _ggk_success: "恭喜您成功刮出盾牌<br/>继续下一步操作吧",
        _ggk_loading: "加载中",
        _ggk_fail: ['呀，盾牌不见了<br/>请', "javascript:noCaptcha.reset()", '再来一次', '或', "http://survey.taobao.com/survey/QgzQDdDd?token=%TOKEN", '反馈问题'],
        _ggk_action_timeout: ['我等得太久啦<br/>请', "javascript:noCaptcha.reset()", '再来一次', '或', "http://survey.taobao.com/survey/QgzQDdDd?token=%TOKEN", '反馈问题'],
        _ggk_net_err: ['网络实在不给力<br/>请', "javascript:noCaptcha.reset()", '再来一次', '或', "http://survey.taobao.com/survey/QgzQDdDd?token=%TOKEN", '反馈问题'],
        _ggk_too_fast: ['您刮得太快啦<br/>请', "javascript:noCaptcha.reset()", '再来一次', '或', "http://survey.taobao.com/survey/QgzQDdDd?token=%TOKEN", '反馈问题']
      }
    }
  }

  const aliscript = document.createElement('script');
  aliscript.setAttribute('type', 'text/javascript');
  aliscript.setAttribute('charset', 'utf-8');
  aliscript.src = "//g.alicdn.com/sd/nvc/1.1.112/guide.js"
  document.body.appendChild(aliscript)
}
// 获取验证码
function getAliCode(phone) {
  //阿里验证sign
  let rSign = window.getNVCVal();
  ajaxFetch("POST", dbgjBase + "/user/sendSms", {
    phone: phone,
    sign: rSign
  }, function (res) {
    const {
      bizStatus,
      code
    } = res;
    if (code === "1") {
      return;
    }
    if (bizStatus === "200" || bizStatus === "100") {
      Message("验证码发送成功")
      dbgjObj.isSendCode = true;
    } else if (bizStatus === "400") {
      //清理倒计时
      MessageBox("请滑动滑块后点确定",
        "<div id='dbgj-fds'></div>"
      );
      //唤醒滑动验证
      getNC().then(function () {
        _nvc_nc.upLang("cn", {
          _startTEXT: "请按住滑块，拖动到最右边",
          _yesTEXT: "验证通过",
          _error300: '哎呀，出错了，点击<a href="javascript:__nc.reset()">刷新</a>再来一次',
          _errorNetwork: '网络不给力，请<a href="javascript:__nc.reset()">点击刷新</a>'
        });
        _nvc_nc.reset();
        // window.clearInterval(clock);
        // self.text("获取验证码");
        // totalTime = 60;
        // self.removeClass("disabled"); //这里重新开启
      });

    } else if (bizStatus === "800" || bizStatus === "900") {
      Message("验证码有问题，请稍后再试", 3, 3000);
      return;
    }
  });
}

// 插入商品详情页的三个工具栏
function injectDetails() {
  const dbgjTool1Node = document.querySelector("#dbgjDetails")
  if (!dbgjTool1Node) {
    return false;
  }
  //创建顶部DealNav
  let DealNavNode = document.createElement("div")
  DealNavNode.id = "dbgj-deal-nav";
  // 创建tool2
  let dbgjTool2Node = document.createElement("div")
  dbgjTool2Node.id = "dbgj-tool2";
  //检测是淘宝还是天猫
  if (dbgjObj.isTmall()) {
    const fqNode = document.querySelector("#content")
    const detailNode = document.querySelector("#detail")
    fqNode.insertBefore(DealNavNode, detailNode)
    // 天猫
    const tmToolBroNode = document.querySelector(".tm-action");
    if (tmToolBroNode && tmToolBroNode.parentNode) {
      const tmToolParNode = tmToolBroNode.parentNode;
      tmToolParNode.appendChild(dbgjTool2Node);
    }
  } else {
    const hdNode = document.querySelector("#J_DcHead")
    const detailNode = document.querySelector("#bd")
    if (hdNode && hdNode.parentNode) {
      const fqNode = hdNode.parentNode
      fqNode.insertBefore(DealNavNode, detailNode)
    }
    // 淘宝
    const tbToolBroNode = document.querySelector(".tb-social");
    if (tbToolBroNode && tbToolBroNode.parentNode) {
      const tbToolParNode = tbToolBroNode.parentNode;
      tbToolParNode.appendChild(dbgjTool2Node);
    }
  }
  DealNavNode.innerHTML = dbgjDetailsTopBarHtml;
  dbgjTool1Node.innerHTML = dbgjTool1Html;
  dbgjTool2Node.innerHTML = dbgjTool2Html;
}

// 插入搜索页面商品底部的item
function injectSearchProductItem() {
  const DavBarNode = document.createElement('div');
  DavBarNode.className = "grid-total";
  if (location.href.indexOf("s.taobao.com") >= 0) {
    const parNode = document.getElementById("main");
    DavBarNode.innerHTML = dbgjSearchTopBarHtml;
    // 搜索页顶部栏
    parNode.insertBefore(DavBarNode, parNode.children[0]);

    let itemList = document.querySelectorAll(".J_ClickStat.J_ItemPicA");
    let idArr = [];
    for (let i = 0; i < itemList.length; i++) {
      idArr.push(itemList[i].getAttribute("data-nid"));
      let injectItemNode = document.createElement('div');
      injectItemNode.className = "dbgj-sousuo-item";
      injectItemNode.id = "dbgj-ssp-id" + itemList[i].getAttribute("data-nid");
      injectItemNode.innerHTML = dbgjSearchItemHtml;
      let parNode = itemList[i].parentNode.parentNode.parentNode.parentNode;
      parNode.style.cssText = "height:auto !important";
      parNode.appendChild(injectItemNode);
    }
    //开启观察者
    let observer = new MutationObserver((nodeList, ob) => {
      nodeList.forEach((item, index) => {
        if (index >= 0) {
          // item.addedNodes[0] 新增的DOM对象
          let itemList = item.addedNodes[0].querySelectorAll(".J_ClickStat.J_ItemPicA");
          let idArr = [];
          for (let i = 0; i < itemList.length; i++) {
            idArr.push(itemList[i].getAttribute("data-nid"));
            let injectItemNode = document.createElement('div');
            injectItemNode.className = "dbgj-sousuo-item";
            injectItemNode.id = "dbgj-ssp-id" + itemList[i].getAttribute("data-nid");
            injectItemNode.innerHTML = dbgjSearchItemHtml;
            let parNode = itemList[i].parentNode.parentNode.parentNode.parentNode;
            parNode.style.cssText = "height:auto !important";
            parNode.appendChild(injectItemNode);
          }
        }
      });
    });
    let gcNode = document.querySelector('#mainsrp-itemlist');
    let options = {
      childList: true,
      attributes: true
    };
    observer.observe(gcNode, options);

    //开启底部观察者
    let robserver = new MutationObserver((nodeList, ob) => {
      nodeList.forEach((item, index) => {
        if (index >= 0) {
          // item.addedNodes[0] 新增的DOM对象
          setTimeout(() => {
            get_p4p_id();
          }, 500);
        }
      });
    });
    let rgcNode = document.querySelector('#J_shopkeeper_bottom');
    let roptions = {
      childList: true,
      attributes: true
    };
    robserver.observe(rgcNode, roptions);
    setTimeout(() => {
      get_p4p_id();
    }, 500);
  }
}
// 查找商品搜索页的右边和底部的商品列表信息
function dbgj_get_itemInfo() {
  let t, e, a, s;
  t = document.getElementsByTagName("html")[0].innerHTML,
    e = /g_page_config = (.*);/g,
    e.exec(t),
    a = RegExp.$1,
    a = JSON.parse(a);
  let i = a.mods.itemlist.data.auctions;
  try {
    s = a.mods.p4p.data.p4pdata
  } catch (t) {
    s = ""
  }
  let n = "",
    d = "";
  if (s) {
    try {
      n = JSON.parse(s).right.data.ds1
    } catch (t) {}
    if (void 0 !== JSON.parse(s).bottom) try {
      d = JSON.parse(s).bottom.data.ds1
    } catch (t) {}
  }
  return {
    itemlist: i,
    p4p_r_data: n,
    p4p_b_data: d
  }
}
// 根据右边和底部的商品列表信息获取id和ww
function get_p4p_id() {
  if (void 0 === window.jsonp_data) {
    let ItemInfo = dbgj_get_itemInfo();
    let rpi = [],
      rpw = [],
      bpi = [],
      bpw = [];
    if (ItemInfo.p4p_r_data) {
      for (let i = 0; i < ItemInfo.p4p_r_data.length; i++) {
        rpi.push(ItemInfo.p4p_r_data[i].RESOURCEID);
        rpw.push(ItemInfo.p4p_r_data[i].WANGWANGID);
      }
      render_r_Item(rpi, rpw);
    }

    if (ItemInfo.p4p_b_data) {
      for (let j = 0; j < ItemInfo.p4p_b_data.length; j++) {
        bpi.push(ItemInfo.p4p_b_data[j].RESOURCEID);
        bpw.push(ItemInfo.p4p_b_data[j].WANGWANGID);
      }
      render_b_Item(bpi, bpw);
      let b_total = 3;
      let b_timerId = setInterval(() => {
        if (b_total === 0) {
          clearInterval(b_timerId);
          return false;
        };
        b_total--;
        render_b_Item(bpi, bpw);
      }, 2000);
    }
  } else {
    let rpi = [],
      rpw = [],
      bpi = [],
      bpw = [];
    let rItemInfo = JSON.parse(window.jsonp_data.p4p.data.p4pdata).right.data.ds1;
    let bItemInfo = JSON.parse(window.jsonp_data.p4p.data.p4pdata).bottom.data.ds1;
    for (let n = 0; n < rItemInfo.length; n++) {
      rpi.push(rItemInfo[n].RESOURCEID);
      rpw.push(rItemInfo[n].WANGWANGID);
    }
    render_r_Item(rpi, rpw);

    for (let k = 0; k < bItemInfo.length; k++) {
      bpi.push(bItemInfo[k].RESOURCEID);
      bpw.push(bItemInfo[k].WANGWANGID);
    }
    render_b_Item(bpi, bpw);
    let b_total = 3;
    let b_timerId = setInterval(() => {
      if (b_total === 0) {
        clearInterval(b_timerId);
        return false;
      };
      b_total--;
      render_b_Item(bpi, bpw);
    }, 2000);
  }
}
// 渲染底部的item
function render_b_Item(iA, wA) {
  if ($("#J_shopkeeper_bottom").length > 0) {
    $.each($("#J_shopkeeper_bottom").find('ul>li[class*="-item"]'), function (i, n) {
      if ($(this).attr("dbgj_p4p_id")) return false;
      let injectItemNode = document.createElement('div');
      injectItemNode.className = "dbgj-sousuo-item";
      injectItemNode.id = "dbgj-ssp-id-" + iA[i];
      injectItemNode.innerHTML = dbgjSearchItemHtml;
      $(this).css("cssText", "height:auto !important");
      $(this).append(injectItemNode);
      $(this).attr("dbgj_p4p_id", iA[i]);
      $(this).attr("dbgj_nick", wA[i]);
      let liH = $(this).height();
      $(this).closest("ul").height(liH);
      $(this).closest('div[class*="-global"]').css("cssText", "height:auto !important");
      let imgH = $(this).find('div[class*="-imgwrap"]').height();
      let feedbackH = imgH - 24;
      $(this).find('div[class*="-feedback"]').css("cssText", "bottom: 0 !important;top:" + feedbackH + "px;");
    });
  }
}
// 渲染右边的item
function render_r_Item(iA, wA) {
  $.each($("#J_shopkeeper").find('tbcc ul>li[class*="-item"]'), function (i, n) {
    if ($(this).attr("dbgj_p4p_id")) return false;
    let injectItemNode = document.createElement('div');
    injectItemNode.className = "dbgj-sousuo-item";
    injectItemNode.id = "dbgj-ssp-id-" + iA[i];
    injectItemNode.innerHTML = dbgjSearchItemHtml;
    $(this).css("cssText", "height:auto !important");
    $(this).append(injectItemNode);
    $(this).attr("dbgj_p4p_id", iA[i]);
    $(this).attr("dbgj_nick", wA[i]);
    let imgH = $(this).find('div[class*="-imgwrap"]').height();
    let feedbackH = imgH - 60;
    let redH = imgH - 75;
    $(this).find('div[class*="-feedback"]').css("cssText", "bottom: 0 !important;top:" + feedbackH + "px;");
    $(this).find('a[class*="-red"]').css("cssText", "bottom: 0 !important;top:" + redH + "px;");
  });
}

// 插件初始化
crxInit();
// 拖拽事件
for(let i=0; i <=11; i++) {
  dbgjObj.dragMove(`dbgj-home-header${i}`, "dbgj-home");
}
